blob: 1ef5ba864eb9d7f2750413fa7711bde0cf083a08 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor213f18b2010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000059 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 }
64
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek1872b312011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek1872b312011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000119 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000120 OnDiskDataMap &M = getOnDiskDataMap();
121 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
122 // We don't worry about freeing the memory associated with OnDiskDataMap.
123 // All we care about is erasing stale files.
124 I->second->Cleanup();
125 }
126}
127
128static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000129 // We require the mutex since we are modifying the structure of the
130 // DenseMap.
131 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000132 OnDiskDataMap &M = getOnDiskDataMap();
133 OnDiskData *&D = M[AU];
134 if (!D)
135 D = new OnDiskData();
136 return *D;
137}
138
139static void erasePreambleFile(const ASTUnit *AU) {
140 getOnDiskData(AU).CleanPreambleFile();
141}
142
143static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000144 // We require the mutex since we are modifying the structure of the
145 // DenseMap.
146 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000147 OnDiskDataMap &M = getOnDiskDataMap();
148 OnDiskDataMap::iterator I = M.find(AU);
149 if (I != M.end()) {
150 I->second->Cleanup();
151 delete I->second;
152 M.erase(AU);
153 }
154}
155
156static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
157 getOnDiskData(AU).PreambleFile = preambleFile;
158}
159
160static const std::string &getPreambleFile(const ASTUnit *AU) {
161 return getOnDiskData(AU).PreambleFile;
162}
163
164void OnDiskData::CleanTemporaryFiles() {
165 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
166 TemporaryFiles[I].eraseFromDisk();
167 TemporaryFiles.clear();
168}
169
170void OnDiskData::CleanPreambleFile() {
171 if (!PreambleFile.empty()) {
172 llvm::sys::Path(PreambleFile).eraseFromDisk();
173 PreambleFile.clear();
174 }
175}
176
177void OnDiskData::Cleanup() {
178 CleanTemporaryFiles();
179 CleanPreambleFile();
180}
181
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000182void ASTUnit::clearFileLevelDecls() {
183 for (FileDeclsTy::iterator
184 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
185 delete I->second;
186 FileDecls.clear();
187}
188
Ted Kremenek1872b312011-10-27 17:55:18 +0000189void ASTUnit::CleanTemporaryFiles() {
190 getOnDiskData(this).CleanTemporaryFiles();
191}
192
193void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
194 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000195}
196
Douglas Gregoreababfb2010-08-04 05:53:38 +0000197/// \brief After failing to build a precompiled preamble (due to
198/// errors in the source that occurs in the preamble), the number of
199/// reparses during which we'll skip even trying to precompile the
200/// preamble.
201const unsigned DefaultPreambleRebuildInterval = 5;
202
Douglas Gregore3c60a72010-11-17 00:13:31 +0000203/// \brief Tracks the number of ASTUnit objects that are currently active.
204///
205/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000206static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000207
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000208ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000209 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000210 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000211 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000212 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000213 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000214 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000215 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000216 ShouldCacheCodeCompletionResults(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000217 CompletionCacheTopLevelHashValue(0),
218 PreambleTopLevelHashValue(0),
219 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000220 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000221 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000222 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000223 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
224 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000225}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000226
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000227ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000228 clearFileLevelDecls();
229
Ted Kremenek1872b312011-10-27 17:55:18 +0000230 // Clean up the temporary files and the preamble file.
231 removeOnDiskEntry(this);
232
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000233 // Free the buffers associated with remapped files. We are required to
234 // perform this operation here because we explicitly request that the
235 // compiler instance *not* free these buffers for each invocation of the
236 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000237 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000238 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
239 for (PreprocessorOptions::remapped_file_buffer_iterator
240 FB = PPOpts.remapped_file_buffer_begin(),
241 FBEnd = PPOpts.remapped_file_buffer_end();
242 FB != FBEnd;
243 ++FB)
244 delete FB->second;
245 }
Douglas Gregor28233422010-07-27 14:52:07 +0000246
247 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000248 delete PreambleBuffer;
249
Douglas Gregor213f18b2010-10-28 15:44:59 +0000250 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000251
252 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000253 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000254 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
255 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000256}
257
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000258void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
259
Douglas Gregor8071e422010-08-15 06:18:01 +0000260/// \brief Determine the set of code-completion contexts in which this
261/// declaration should be shown.
262static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000263 const LangOptions &LangOpts,
264 bool &IsNestedNameSpecifier) {
265 IsNestedNameSpecifier = false;
266
Douglas Gregor8071e422010-08-15 06:18:01 +0000267 if (isa<UsingShadowDecl>(ND))
268 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
269 if (!ND)
270 return 0;
271
272 unsigned Contexts = 0;
273 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
274 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
275 // Types can appear in these contexts.
276 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
277 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
279 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
280 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000281 | (1 << (CodeCompletionContext::CCC_Type - 1))
282 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000283
284 // In C++, types can appear in expressions contexts (for functional casts).
285 if (LangOpts.CPlusPlus)
286 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
287
288 // In Objective-C, message sends can send interfaces. In Objective-C++,
289 // all types are available due to functional casts.
290 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
291 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000292
293 // In Objective-C, you can only be a subclass of another Objective-C class
294 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000295 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000296
297 // Deal with tag names.
298 if (isa<EnumDecl>(ND)) {
299 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
300
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000301 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000302 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000304 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
305 if (Record->isUnion())
306 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
307 else
308 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
309
Douglas Gregor8071e422010-08-15 06:18:01 +0000310 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000311 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000312 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
315 // Values can appear in these contexts.
316 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
317 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000318 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000319 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
320 } else if (isa<ObjCProtocolDecl>(ND)) {
321 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000322 } else if (isa<ObjCCategoryDecl>(ND)) {
323 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000325 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000326
327 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000328 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000329 }
330
331 return Contexts;
332}
333
Douglas Gregor87c08a52010-08-13 22:48:40 +0000334void ASTUnit::CacheCodeCompletionResults() {
335 if (!TheSema)
336 return;
337
Douglas Gregor213f18b2010-10-28 15:44:59 +0000338 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000339 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000340
341 // Clear out the previous results.
342 ClearCachedCompletionResults();
343
344 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000345 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000346 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000347 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
349 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350
351 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
353
Douglas Gregor87c08a52010-08-13 22:48:40 +0000354 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
355 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000356 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000357 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000358 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000359 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000360 *CachedCompletionAllocator,
361 getCodeCompletionTUInfo());
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000363 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000364 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000365 CachedResult.Priority = Results[I].Priority;
366 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000367 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000368
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 // Keep track of the type of this completion in an ASTContext-agnostic
370 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000371 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000372 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000373 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 CachedResult.Type = 0;
375 } else {
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
379
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
387 = TypeValue;
388 }
389
390 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392
Douglas Gregor8071e422010-08-15 06:18:01 +0000393 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000394
395 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000396 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000397 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
398 // The contexts in which a nested-name-specifier can appear in C++.
399 unsigned NNSContexts
400 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
401 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
402 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
403 | (1 << (CodeCompletionContext::CCC_Statement - 1))
404 | (1 << (CodeCompletionContext::CCC_Expression - 1))
405 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
406 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
407 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
408 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000409 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000410 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
411 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000412
413 if (isa<NamespaceDecl>(Results[I].Declaration) ||
414 isa<NamespaceAliasDecl>(Results[I].Declaration))
415 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
416
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
422 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000423 CachedResult.Completion
424 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000425 *CachedCompletionAllocator,
426 getCodeCompletionTUInfo());
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000427 CachedResult.ShowInContexts = RemainingContexts;
428 CachedResult.Priority = CCP_NestedNameSpecifier;
429 CachedResult.TypeClass = STC_Void;
430 CachedResult.Type = 0;
431 CachedCompletionResults.push_back(CachedResult);
432 }
433 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000434 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000435 }
436
Douglas Gregor87c08a52010-08-13 22:48:40 +0000437 case Result::RK_Keyword:
438 case Result::RK_Pattern:
439 // Ignore keywords and patterns; we don't care, since they are so
440 // easily regenerated.
441 break;
442
443 case Result::RK_Macro: {
444 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000445 CachedResult.Completion
446 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000447 *CachedCompletionAllocator,
448 getCodeCompletionTUInfo());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 CachedResult.ShowInContexts
450 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
451 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
453 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
454 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
455 | (1 << (CodeCompletionContext::CCC_Statement - 1))
456 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000457 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000458 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000459 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000460 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
461 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000462
Douglas Gregor87c08a52010-08-13 22:48:40 +0000463 CachedResult.Priority = Results[I].Priority;
464 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000465 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000466 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000467 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000468 CachedCompletionResults.push_back(CachedResult);
469 break;
470 }
471 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000472 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000473
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476}
477
478void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000479 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000481 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482}
483
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000484namespace {
485
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000486/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000488class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000489 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000490 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
492 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000493 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494 std::string &Predefines;
495 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000499 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000501 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
502 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000503 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000504 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000506 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000507 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000508 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000512 return false;
513
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000515
516 // Initialize the preprocessor.
517 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518
519 // Initialize the ASTContext
520 Context.InitBuiltinTypes(*Target);
521
522 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner5f9e2722011-07-23 10:55:15 +0000526 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000527 // If we've already initialized the target, don't do it again.
528 if (Target)
529 return false;
530
531 // FIXME: This is broken, we should store the TargetOptions in the AST file.
532 TargetOptions TargetOpts;
533 TargetOpts.ABI = "";
534 TargetOpts.CXXABI = "";
535 TargetOpts.CPU = "";
536 TargetOpts.Features.clear();
537 TargetOpts.Triple = Triple;
538 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000539 return false;
540 }
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000542 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000543 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000544 std::string &SuggestedPredefines,
545 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000546 Predefines = Buffers[0].Data;
547 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
548 Predefines += Buffers[I].Data;
549 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000553 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000557 virtual void ReadCounter(unsigned Value) {
558 Counter = Value;
559 }
560};
561
David Blaikie26e7a902011-09-26 00:01:39 +0000562class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000563 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000564
565public:
David Blaikie26e7a902011-09-26 00:01:39 +0000566 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000567 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000568 : StoredDiags(StoredDiags) { }
569
David Blaikied6471f72011-09-25 23:23:43 +0000570 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000571 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000572
573 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
574 // Just drop any diagnostics that come from cloned consumers; they'll
575 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000576 // FIXME: We'd like to be able to capture these somehow, even if it's just
577 // file/line/column, because they could occur when parsing module maps or
578 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000579 return new IgnoringDiagConsumer();
580 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000581};
582
583/// \brief RAII object that optionally captures diagnostics, if
584/// there is no diagnostic client to capture them already.
585class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000586 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000587 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000588 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000589
590public:
David Blaikied6471f72011-09-25 23:23:43 +0000591 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000592 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000593 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000594 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000595 if (RequestCapture || Diags.getClient() == 0) {
596 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000598 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000599 }
600
601 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000602 if (Diags.getClient() == &Client) {
603 Diags.takeClient();
604 Diags.setClient(PreviousClient);
605 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000606 }
607};
608
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000609} // anonymous namespace
610
David Blaikie26e7a902011-09-26 00:01:39 +0000611void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000612 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000613 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000614 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000615
Douglas Gregora88084b2010-02-18 18:08:43 +0000616 StoredDiags.push_back(StoredDiagnostic(Level, Info));
617}
618
Steve Naroff77accc12009-09-03 18:19:54 +0000619const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000620 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000621}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000622
Chris Lattner5f9e2722011-07-23 10:55:15 +0000623llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000624 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000625 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000626 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000627}
628
Douglas Gregore47be3e2010-11-11 00:39:14 +0000629/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000630void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000631 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000632 ASTUnit &AST, bool CaptureDiagnostics) {
633 if (!Diags.getPtr()) {
634 // No diagnostics engine was provided, so create our own diagnostics object
635 // with the default options.
636 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000637 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000638 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000639 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000640 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
641 ArgBegin, Client,
642 /*ShouldOwnClient=*/true,
643 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000644 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000645 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000646 }
647}
648
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000649ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000650 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000651 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000652 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000653 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000654 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000655 bool CaptureDiagnostics,
656 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000657 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000658
659 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000660 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
661 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000662 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
663 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000664 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000665
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000666 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000667
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000668 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000670 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000671 AST->FileMgr = new FileManager(FileSystemOpts);
672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
673 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000674 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000675 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000676 AST->ASTFileLangOpts,
677 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000678
Douglas Gregor4db64a42010-01-23 00:14:00 +0000679 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000680 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
681 if (const llvm::MemoryBuffer *
682 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
683 // Create the file entry for the file that we're mapping from.
684 const FileEntry *FromFile
685 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
686 memBuf->getBufferSize(),
687 0);
688 if (!FromFile) {
689 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
690 << RemappedFiles[I].first;
691 delete memBuf;
692 continue;
693 }
694
695 // Override the contents of the "from" file with the contents of
696 // the "to" file.
697 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
698
699 } else {
700 const char *fname = fileOrBuf.get<const char *>();
701 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
702 if (!ToFile) {
703 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
704 << RemappedFiles[I].first << fname;
705 continue;
706 }
707
708 // Create the file entry for the file that we're mapping from.
709 const FileEntry *FromFile
710 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
711 ToFile->getSize(),
712 0);
713 if (!FromFile) {
714 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
715 << RemappedFiles[I].first;
716 delete memBuf;
717 continue;
718 }
719
720 // Override the contents of the "from" file with the contents of
721 // the "to" file.
722 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000723 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000724 }
725
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000726 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000728 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000729 std::string Predefines;
730 unsigned Counter;
731
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000732 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000733
Douglas Gregor998b3d32011-09-01 23:39:15 +0000734 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
735 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
736 *AST,
737 /*IILookup=*/0,
738 /*OwnsHeaderSearch=*/false,
739 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000740 Preprocessor &PP = *AST->PP;
741
742 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
743 AST->getSourceManager(),
744 /*Target=*/0,
745 PP.getIdentifierTable(),
746 PP.getSelectorTable(),
747 PP.getBuiltinInfo(),
748 /* size_reserve = */0,
749 /*DelayInitialization=*/true);
750 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000751
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000752 Reader.reset(new ASTReader(PP, Context,
753 /*isysroot=*/"",
754 /*DisableValidation=*/false,
755 /*DisableStatCache=*/false,
756 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000757
758 // Recover resources if we crash before exiting this method.
759 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
760 ReaderCleanup(Reader.get());
761
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000762 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000763 AST->ASTFileLangOpts, HeaderInfo,
764 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000765
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000766 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000767 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000770 case ASTReader::Failure:
771 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000772 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000773 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000776 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
777
Daniel Dunbard5b61262009-09-21 03:03:47 +0000778 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000779 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000781 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000782 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000783 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000784 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000785 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000786
787 // Unregister the cleanup for ASTReader. It will get cleaned up
788 // by the ASTUnit cleanup.
789 ReaderCleanup.unregister();
790
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000791 Context.setExternalSource(Source);
792
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000793 // Create an AST consumer, even though it isn't used.
794 AST->Consumer.reset(new ASTConsumer);
795
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000796 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000797 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
798 AST->TheSema->Initialize();
799 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000800 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000801
Mike Stump1eb44332009-09-09 15:08:12 +0000802 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000803}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000804
805namespace {
806
Douglas Gregor9b7db622011-02-16 18:16:54 +0000807/// \brief Preprocessor callback class that updates a hash value with the names
808/// of all macros that have been defined by the translation unit.
809class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
810 unsigned &Hash;
811
812public:
813 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
814
815 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
816 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
817 }
818};
819
820/// \brief Add the given declaration to the hash of all top-level entities.
821void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
822 if (!D)
823 return;
824
825 DeclContext *DC = D->getDeclContext();
826 if (!DC)
827 return;
828
829 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
830 return;
831
832 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
833 if (ND->getIdentifier())
834 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
835 else if (DeclarationName Name = ND->getDeclName()) {
836 std::string NameStr = Name.getAsString();
837 Hash = llvm::HashString(NameStr, Hash);
838 }
839 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000840 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000841}
842
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000843class TopLevelDeclTrackerConsumer : public ASTConsumer {
844 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000845 unsigned &Hash;
846
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000847public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000848 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
849 : Unit(_Unit), Hash(Hash) {
850 Hash = 0;
851 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000852
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000853 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000854 if (!D)
855 return;
856
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000857 // FIXME: Currently ObjC method declarations are incorrectly being
858 // reported as top-level declarations, even though their DeclContext
859 // is the containing ObjC @interface/@implementation. This is a
860 // fundamental problem in the parser right now.
861 if (isa<ObjCMethodDecl>(D))
862 return;
863
864 AddTopLevelDeclarationToHash(D, Hash);
865 Unit.addTopLevelDecl(D);
866
867 handleFileLevelDecl(D);
868 }
869
870 void handleFileLevelDecl(Decl *D) {
871 Unit.addFileLevelDecl(D);
872 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
873 for (NamespaceDecl::decl_iterator
874 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
875 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000876 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000877 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000878
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000879 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000880 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
881 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000882 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000883 }
884
Sebastian Redl27372b42010-08-11 18:52:41 +0000885 // We're not interested in "interesting" decls.
886 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000887
888 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
889 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
890 handleTopLevelDecl(*it);
891 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000892};
893
894class TopLevelDeclTrackerAction : public ASTFrontendAction {
895public:
896 ASTUnit &Unit;
897
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000898 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000899 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000900 CI.getPreprocessor().addPPCallbacks(
901 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
902 return new TopLevelDeclTrackerConsumer(Unit,
903 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000904 }
905
906public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000907 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
908
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000909 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000910 virtual TranslationUnitKind getTranslationUnitKind() {
911 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000912 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000913};
914
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000915class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000916 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000917 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000918 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000919
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000920public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000921 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000922 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000923 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000924 Hash(Unit.getCurrentTopLevelHashValue()) {
925 Hash = 0;
926 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000927
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000928 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000929 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
930 Decl *D = *it;
931 // FIXME: Currently ObjC method declarations are incorrectly being
932 // reported as top-level declarations, even though their DeclContext
933 // is the containing ObjC @interface/@implementation. This is a
934 // fundamental problem in the parser right now.
935 if (isa<ObjCMethodDecl>(D))
936 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000937 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000938 TopLevelDecls.push_back(D);
939 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000940 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000941 }
942
943 virtual void HandleTranslationUnit(ASTContext &Ctx) {
944 PCHGenerator::HandleTranslationUnit(Ctx);
945 if (!Unit.getDiagnostics().hasErrorOccurred()) {
946 // Translate the top-level declarations we captured during
947 // parsing into declaration IDs in the precompiled
948 // preamble. This will allow us to deserialize those top-level
949 // declarations when requested.
950 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
951 Unit.addTopLevelDeclFromPreamble(
952 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000953 }
954 }
955};
956
957class PrecompilePreambleAction : public ASTFrontendAction {
958 ASTUnit &Unit;
959
960public:
961 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
962
963 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000964 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000965 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000966 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000967 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000968 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
969 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000970 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000971 return 0;
972
Douglas Gregor832d6202011-07-22 16:35:34 +0000973 if (!CI.getFrontendOpts().RelocatablePCH)
974 Sysroot.clear();
975
Douglas Gregor9b7db622011-02-16 18:16:54 +0000976 CI.getPreprocessor().addPPCallbacks(
977 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000978 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
979 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000980 }
981
982 virtual bool hasCodeCompletionSupport() const { return false; }
983 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000984 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000985};
986
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000987}
988
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000989static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
990 StoredDiagnostics) {
991 // Get rid of stored diagnostics except the ones from the driver which do not
992 // have a source location.
993 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
994 if (StoredDiagnostics[I].getLocation().isValid()) {
995 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
996 --I;
997 }
998 }
999}
1000
1001static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1002 StoredDiagnostics,
1003 SourceManager &SM) {
1004 // The stored diagnostic has the old source manager in it; update
1005 // the locations to refer into the new source manager. Since we've
1006 // been careful to make sure that the source manager's state
1007 // before and after are identical, so that we can reuse the source
1008 // location itself.
1009 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1010 if (StoredDiagnostics[I].getLocation().isValid()) {
1011 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1012 StoredDiagnostics[I].setLocation(Loc);
1013 }
1014 }
1015}
1016
Douglas Gregorabc563f2010-07-19 21:46:24 +00001017/// Parse the source file into a translation unit using the given compiler
1018/// invocation, replacing the current translation unit.
1019///
1020/// \returns True if a failure occurred that causes the ASTUnit not to
1021/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001022bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001023 delete SavedMainFileBuffer;
1024 SavedMainFileBuffer = 0;
1025
Ted Kremenek4f327862011-03-21 18:40:17 +00001026 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001027 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001028 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001029 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001030
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001031 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001032 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001033
1034 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001035 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1036 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001038 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001039 CCInvocation(new CompilerInvocation(*Invocation));
1040
1041 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001042 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001043
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001044 // Set up diagnostics, capturing any diagnostics that would
1045 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001046 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001047
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001048 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001049 Clang->getTargetOpts().Features = TargetFeatures;
1050 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001051 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001052 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001053 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001054 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001055 }
1056
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001057 // Inform the target of the language options.
1058 //
1059 // FIXME: We shouldn't need to do this, the target should be immutable once
1060 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001061 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001062
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001064 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001065 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001066 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001067 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001068 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001069
Douglas Gregorabc563f2010-07-19 21:46:24 +00001070 // Configure the various subsystems.
1071 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001072 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001073 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001074 FileMgr = new FileManager(FileSystemOpts);
1075 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001076 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001077 Ctx = 0;
1078 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001079 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001080
1081 // Clear out old caches and data.
1082 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001083 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001084 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001085
Douglas Gregorf128fed2010-08-20 00:02:33 +00001086 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001087 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001088 TopLevelDeclsInPreamble.clear();
1089 }
1090
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001091 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001092 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001093
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001094 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001095 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001096
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001097 // If the main file has been overridden due to the use of a preamble,
1098 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001100 if (OverrideMainBuffer) {
1101 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1102 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1103 PreprocessorOpts.PrecompiledPreambleBytes.second
1104 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001105 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001106 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001107
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001108 // The stored diagnostic has the old source manager in it; update
1109 // the locations to refer into the new source manager. Since we've
1110 // been careful to make sure that the source manager's state
1111 // before and after are identical, so that we can reuse the source
1112 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001113 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001114
1115 // Keep track of the override buffer;
1116 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001117 }
1118
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001119 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001120 new TopLevelDeclTrackerAction(*this));
1121
1122 // Recover resources if we crash before exiting this method.
1123 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1124 ActCleanup(Act.get());
1125
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001126 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001127 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001128
1129 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001130 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001131 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1132 getSourceManager(), PreambleDiagnostics,
1133 StoredDiagnostics);
1134 }
1135
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001136 if (!Act->Execute())
1137 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001138
1139 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001140
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001141 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001142
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001143 FailedParseDiagnostics.clear();
1144
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001146
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001147error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001148 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001149 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001150 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001151 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001152 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001153
1154 // Keep the ownership of the data in the ASTUnit because the client may
1155 // want to see the diagnostics.
1156 transferASTDataFromCompilerInstance(*Clang);
1157 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001158 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001159 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001160 return true;
1161}
1162
Douglas Gregor44c181a2010-07-23 00:33:23 +00001163/// \brief Simple function to retrieve a path for a preamble precompiled header.
1164static std::string GetPreamblePCHPath() {
1165 // FIXME: This is lame; sys::Path should provide this function (in particular,
1166 // it should know how to find the temporary files dir).
1167 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001168 // FIXME: This is a hack so that we can override the preamble file during
1169 // crash-recovery testing, which is the only case where the preamble files
1170 // are not necessarily cleaned up.
1171 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1172 if (TmpFile)
1173 return TmpFile;
1174
Douglas Gregor44c181a2010-07-23 00:33:23 +00001175 std::string Error;
1176 const char *TmpDir = ::getenv("TMPDIR");
1177 if (!TmpDir)
1178 TmpDir = ::getenv("TEMP");
1179 if (!TmpDir)
1180 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001181#ifdef LLVM_ON_WIN32
1182 if (!TmpDir)
1183 TmpDir = ::getenv("USERPROFILE");
1184#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001185 if (!TmpDir)
1186 TmpDir = "/tmp";
1187 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001188 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001190 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001191 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 return std::string();
1193
Douglas Gregor44c181a2010-07-23 00:33:23 +00001194 return P.str();
1195}
1196
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001197/// \brief Compute the preamble for the main file, providing the source buffer
1198/// that corresponds to the main file along with a pair (bytes, start-of-line)
1199/// that describes the preamble.
1200std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001201ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1202 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001203 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001204 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001205 CreatedBuffer = false;
1206
Douglas Gregor44c181a2010-07-23 00:33:23 +00001207 // Try to determine if the main file has been remapped, either from the
1208 // command line (to another file) or directly through the compiler invocation
1209 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001211 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001212 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1213 // Check whether there is a file-file remapping of the main file
1214 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001215 M = PreprocessorOpts.remapped_file_begin(),
1216 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 M != E;
1218 ++M) {
1219 llvm::sys::PathWithStatus MPath(M->first);
1220 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1221 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1222 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001223 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001225 CreatedBuffer = false;
1226 }
1227
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001228 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001230 return std::make_pair((llvm::MemoryBuffer*)0,
1231 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001232 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 }
1234 }
1235 }
1236
1237 // Check whether there is a file-buffer remapping. It supercedes the
1238 // file-file remapping.
1239 for (PreprocessorOptions::remapped_file_buffer_iterator
1240 M = PreprocessorOpts.remapped_file_buffer_begin(),
1241 E = PreprocessorOpts.remapped_file_buffer_end();
1242 M != E;
1243 ++M) {
1244 llvm::sys::PathWithStatus MPath(M->first);
1245 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1246 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1247 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001248 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001249 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001250 CreatedBuffer = false;
1251 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252
Douglas Gregor175c4a92010-07-23 23:58:40 +00001253 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001254 }
1255 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 }
1258
1259 // If the main source file was not remapped, load it now.
1260 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001261 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001262 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001263 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264
1265 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 }
1267
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001268 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001269 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001270 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001271}
1272
Douglas Gregor754f3492010-07-24 00:38:13 +00001273static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001274 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001275 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001276 llvm::MemoryBuffer *Result
1277 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1278 memcpy(const_cast<char*>(Result->getBufferStart()),
1279 Old->getBufferStart(), Old->getBufferSize());
1280 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001281 ' ', NewSize - Old->getBufferSize() - 1);
1282 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001283
Douglas Gregor754f3492010-07-24 00:38:13 +00001284 return Result;
1285}
1286
Douglas Gregor175c4a92010-07-23 23:58:40 +00001287/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1288/// the source file.
1289///
1290/// This routine will compute the preamble of the main source file. If a
1291/// non-trivial preamble is found, it will precompile that preamble into a
1292/// precompiled header so that the precompiled preamble can be used to reduce
1293/// reparsing time. If a precompiled preamble has already been constructed,
1294/// this routine will determine if it is still valid and, if so, avoid
1295/// rebuilding the precompiled preamble.
1296///
Douglas Gregordf95a132010-08-09 20:45:32 +00001297/// \param AllowRebuild When true (the default), this routine is
1298/// allowed to rebuild the precompiled preamble if it is found to be
1299/// out-of-date.
1300///
1301/// \param MaxLines When non-zero, the maximum number of lines that
1302/// can occur within the preamble.
1303///
Douglas Gregor754f3492010-07-24 00:38:13 +00001304/// \returns If the precompiled preamble can be used, returns a newly-allocated
1305/// buffer that should be used in place of the main file when doing so.
1306/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001307llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001308 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001309 bool AllowRebuild,
1310 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001311
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001312 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001313 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1314 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001316 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317
1318 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001319 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001320 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001321
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001322 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001323 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001324 if (CreatedPreambleBuffer)
1325 OwnedPreambleBuffer.reset(NewPreamble.first);
1326
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001327 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001328 // We couldn't find a preamble in the main source. Clear out the current
1329 // preamble, if we have one. It's obviously no good any more.
1330 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001331 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001332
1333 // The next time we actually see a preamble, precompile it.
1334 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001335 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001336 }
1337
1338 if (!Preamble.empty()) {
1339 // We've previously computed a preamble. Check whether we have the same
1340 // preamble now that we did before, and that there's enough space in
1341 // the main-file buffer within the precompiled preamble to fit the
1342 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001343 if (Preamble.size() == NewPreamble.second.first &&
1344 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001345 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001346 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001347 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001348 // The preamble has not changed. We may be able to re-use the precompiled
1349 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001350
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001351 // Check that none of the files used by the preamble have changed.
1352 bool AnyFileChanged = false;
1353
1354 // First, make a record of those files that have been overridden via
1355 // remapping or unsaved_files.
1356 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1357 for (PreprocessorOptions::remapped_file_iterator
1358 R = PreprocessorOpts.remapped_file_begin(),
1359 REnd = PreprocessorOpts.remapped_file_end();
1360 !AnyFileChanged && R != REnd;
1361 ++R) {
1362 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001363 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001364 // If we can't stat the file we're remapping to, assume that something
1365 // horrible happened.
1366 AnyFileChanged = true;
1367 break;
1368 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001369
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001370 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1371 StatBuf.st_mtime);
1372 }
1373 for (PreprocessorOptions::remapped_file_buffer_iterator
1374 R = PreprocessorOpts.remapped_file_buffer_begin(),
1375 REnd = PreprocessorOpts.remapped_file_buffer_end();
1376 !AnyFileChanged && R != REnd;
1377 ++R) {
1378 // FIXME: Should we actually compare the contents of file->buffer
1379 // remappings?
1380 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1381 0);
1382 }
1383
1384 // Check whether anything has changed.
1385 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1386 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1387 !AnyFileChanged && F != FEnd;
1388 ++F) {
1389 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1390 = OverriddenFiles.find(F->first());
1391 if (Overridden != OverriddenFiles.end()) {
1392 // This file was remapped; check whether the newly-mapped file
1393 // matches up with the previous mapping.
1394 if (Overridden->second != F->second)
1395 AnyFileChanged = true;
1396 continue;
1397 }
1398
1399 // The file was not remapped; check whether it has changed on disk.
1400 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001401 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001402 // If we can't stat the file, assume that something horrible happened.
1403 AnyFileChanged = true;
1404 } else if (StatBuf.st_size != F->second.first ||
1405 StatBuf.st_mtime != F->second.second)
1406 AnyFileChanged = true;
1407 }
1408
1409 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001410 // Okay! We can re-use the precompiled preamble.
1411
1412 // Set the state of the diagnostic object to mimic its state
1413 // after parsing the preamble.
1414 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001415 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001416 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001417 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001418
1419 // Create a version of the main file buffer that is padded to
1420 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001422 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001423 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001424 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001425 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001426
1427 // If we aren't allowed to rebuild the precompiled preamble, just
1428 // return now.
1429 if (!AllowRebuild)
1430 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001431
Douglas Gregor175c4a92010-07-23 23:58:40 +00001432 // We can't reuse the previously-computed preamble. Build a new one.
1433 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001434 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001435 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001436 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001437 } else if (!AllowRebuild) {
1438 // We aren't allowed to rebuild the precompiled preamble; just
1439 // return now.
1440 return 0;
1441 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001442
1443 // If the preamble rebuild counter > 1, it's because we previously
1444 // failed to build a preamble and we're not yet ready to try
1445 // again. Decrement the counter and return a failure.
1446 if (PreambleRebuildCounter > 1) {
1447 --PreambleRebuildCounter;
1448 return 0;
1449 }
1450
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001451 // Create a temporary file for the precompiled preamble. In rare
1452 // circumstances, this can fail.
1453 std::string PreamblePCHPath = GetPreamblePCHPath();
1454 if (PreamblePCHPath.empty()) {
1455 // Try again next time.
1456 PreambleRebuildCounter = 1;
1457 return 0;
1458 }
1459
Douglas Gregor175c4a92010-07-23 23:58:40 +00001460 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001461 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001462 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001463
1464 // Create a new buffer that stores the preamble. The buffer also contains
1465 // extra space for the original contents of the file (which will be present
1466 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001467 // grows.
1468 PreambleReservedSize = NewPreamble.first->getBufferSize();
1469 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001470 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001471 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001472 PreambleReservedSize *= 2;
1473
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001474 // Save the preamble text for later; we'll need to compare against it for
1475 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001476 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001477 Preamble.assign(FileMgr->getFile(MainFilename),
1478 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001479 NewPreamble.first->getBufferStart()
1480 + NewPreamble.second.first);
1481 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1482
Douglas Gregor671947b2010-08-19 01:33:06 +00001483 delete PreambleBuffer;
1484 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001485 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001486 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001487 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001488 NewPreamble.first->getBufferStart(), Preamble.size());
1489 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001490 ' ', PreambleReservedSize - Preamble.size() - 1);
1491 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001492
1493 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001494 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1496
1497 // Tell the compiler invocation to generate a temporary precompiled header.
1498 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001499 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001500 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001501 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1502 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001503
1504 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001505 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001506
1507 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001508 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1509 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001510
Douglas Gregor01b6e312011-07-01 18:22:13 +00001511 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001512 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001513
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001514 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001515 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
1517 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001518 Clang->getTargetOpts().Features = TargetFeatures;
1519 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1520 Clang->getTargetOpts()));
1521 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001522 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1523 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001524 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001525 PreprocessorOpts.eraseRemappedFile(
1526 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001527 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001528 }
1529
1530 // Inform the target of the language options.
1531 //
1532 // FIXME: We shouldn't need to do this, the target should be immutable once
1533 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001534 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001535
Ted Kremenek03201fb2011-03-21 18:40:07 +00001536 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001538 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001539 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001540 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541 "IR inputs not support here!");
1542
1543 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001544 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001545 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001546 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001547 TopLevelDecls.clear();
1548 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001549
1550 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001551 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552
1553 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001555 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001557 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001558 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001559 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001560 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1561 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001562 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001563 PreprocessorOpts.eraseRemappedFile(
1564 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001565 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566 }
1567
1568 Act->Execute();
1569 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001570
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001571 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001572 // There were errors parsing the preamble, so no precompiled header was
1573 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001574 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001575 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1576 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001577 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001578 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001579 PreprocessorOpts.eraseRemappedFile(
1580 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001581 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001582 }
1583
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001584 // Transfer any diagnostics generated when parsing the preamble into the set
1585 // of preamble diagnostics.
1586 PreambleDiagnostics.clear();
1587 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001588 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001589 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001590
Douglas Gregor175c4a92010-07-23 23:58:40 +00001591 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001592 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001593 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001594
1595 // Keep track of all of the files that the source manager knows about,
1596 // so we can verify whether they have changed or not.
1597 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001598 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001599 const llvm::MemoryBuffer *MainFileBuffer
1600 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1601 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1602 FEnd = SourceMgr.fileinfo_end();
1603 F != FEnd;
1604 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001605 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001606 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1607 continue;
1608
1609 FilesInPreamble[File->getName()]
1610 = std::make_pair(F->second->getSize(), File->getModificationTime());
1611 }
1612
Douglas Gregoreababfb2010-08-04 05:53:38 +00001613 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001614 PreprocessorOpts.eraseRemappedFile(
1615 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001616
1617 // If the hash of top-level entities differs from the hash of the top-level
1618 // entities the last time we rebuilt the preamble, clear out the completion
1619 // cache.
1620 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1621 CompletionCacheTopLevelHashValue = 0;
1622 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1623 }
1624
Douglas Gregor754f3492010-07-24 00:38:13 +00001625 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001626 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001627 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001628}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001629
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001630void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1631 std::vector<Decl *> Resolved;
1632 Resolved.reserve(TopLevelDeclsInPreamble.size());
1633 ExternalASTSource &Source = *getASTContext().getExternalSource();
1634 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1635 // Resolve the declaration ID to an actual declaration, possibly
1636 // deserializing the declaration in the process.
1637 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1638 if (D)
1639 Resolved.push_back(D);
1640 }
1641 TopLevelDeclsInPreamble.clear();
1642 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1643}
1644
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001645void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1646 // Steal the created target, context, and preprocessor.
1647 TheSema.reset(CI.takeSema());
1648 Consumer.reset(CI.takeASTConsumer());
1649 Ctx = &CI.getASTContext();
1650 PP = &CI.getPreprocessor();
1651 CI.setSourceManager(0);
1652 CI.setFileManager(0);
1653 Target = &CI.getTarget();
1654 Reader = CI.getModuleManager();
1655}
1656
Chris Lattner5f9e2722011-07-23 10:55:15 +00001657StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001658 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001659}
1660
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001661ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001662 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001663 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001664 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001665 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001666 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001667 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001668 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001669 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001670 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001671 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001672
1673 return AST.take();
1674}
1675
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001676ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001677 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001678 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001679 ASTUnit *Unit,
1680 bool Persistent,
1681 StringRef ResourceFilesPath,
1682 bool OnlyLocalDecls,
1683 bool CaptureDiagnostics,
1684 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001685 bool CacheCodeCompletionResults,
1686 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001687 assert(CI && "A CompilerInvocation is required");
1688
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001689 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001690 ASTUnit *AST = Unit;
1691 if (!AST) {
1692 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001693 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001694 AST = OwnAST.get();
1695 }
1696
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001697 if (!ResourceFilesPath.empty()) {
1698 // Override the resources path.
1699 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1700 }
1701 AST->OnlyLocalDecls = OnlyLocalDecls;
1702 AST->CaptureDiagnostics = CaptureDiagnostics;
1703 if (PrecompilePreamble)
1704 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001705 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001706 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001707
1708 // Recover resources if we crash before exiting this method.
1709 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001710 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001711 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1712 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001713 DiagCleanup(Diags.getPtr());
1714
1715 // We'll manage file buffers ourselves.
1716 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1717 CI->getFrontendOpts().DisableFree = false;
1718 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1719
1720 // Save the target features.
1721 AST->TargetFeatures = CI->getTargetOpts().Features;
1722
1723 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001724 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001725
1726 // Recover resources if we crash before exiting this method.
1727 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1728 CICleanup(Clang.get());
1729
1730 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001731 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001732
1733 // Set up diagnostics, capturing any diagnostics that would
1734 // otherwise be dropped.
1735 Clang->setDiagnostics(&AST->getDiagnostics());
1736
1737 // Create the target instance.
1738 Clang->getTargetOpts().Features = AST->TargetFeatures;
1739 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1740 Clang->getTargetOpts()));
1741 if (!Clang->hasTarget())
1742 return 0;
1743
1744 // Inform the target of the language options.
1745 //
1746 // FIXME: We shouldn't need to do this, the target should be immutable once
1747 // created. This complexity should be lifted elsewhere.
1748 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1749
1750 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1751 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001752 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001753 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001754 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001755 "IR inputs not supported here!");
1756
1757 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 AST->TheSema.reset();
1759 AST->Ctx = 0;
1760 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001761 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001762
1763 // Create a file manager object to provide access to and cache the filesystem.
1764 Clang->setFileManager(&AST->getFileManager());
1765
1766 // Create the source manager.
1767 Clang->setSourceManager(&AST->getSourceManager());
1768
1769 ASTFrontendAction *Act = Action;
1770
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001771 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001772 if (!Act) {
1773 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1774 Act = TrackerAct.get();
1775 }
1776
1777 // Recover resources if we crash before exiting this method.
1778 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1779 ActCleanup(TrackerAct.get());
1780
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001781 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1782 AST->transferASTDataFromCompilerInstance(*Clang);
1783 if (OwnAST && ErrAST)
1784 ErrAST->swap(OwnAST);
1785
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001786 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001787 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001788
1789 if (Persistent && !TrackerAct) {
1790 Clang->getPreprocessor().addPPCallbacks(
1791 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1792 std::vector<ASTConsumer*> Consumers;
1793 if (Clang->hasASTConsumer())
1794 Consumers.push_back(Clang->takeASTConsumer());
1795 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1796 AST->getCurrentTopLevelHashValue()));
1797 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1798 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001799 if (!Act->Execute()) {
1800 AST->transferASTDataFromCompilerInstance(*Clang);
1801 if (OwnAST && ErrAST)
1802 ErrAST->swap(OwnAST);
1803
1804 return 0;
1805 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001806
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001807 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001808 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001809
1810 Act->EndSourceFile();
1811
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001812 if (OwnAST)
1813 return OwnAST.take();
1814 else
1815 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001816}
1817
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001818bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1819 if (!Invocation)
1820 return true;
1821
1822 // We'll manage file buffers ourselves.
1823 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1824 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001825 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001826
Douglas Gregor1aa27302011-01-27 18:02:58 +00001827 // Save the target features.
1828 TargetFeatures = Invocation->getTargetOpts().Features;
1829
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001830 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001831 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001832 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001833 OverrideMainBuffer
1834 = getMainBufferWithPrecompiledPreamble(*Invocation);
1835 }
1836
Douglas Gregor213f18b2010-10-28 15:44:59 +00001837 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001838 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001839
Ted Kremenek25a11e12011-03-22 01:15:24 +00001840 // Recover resources if we crash before exiting this method.
1841 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1842 MemBufferCleanup(OverrideMainBuffer);
1843
Douglas Gregor213f18b2010-10-28 15:44:59 +00001844 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001845}
1846
Douglas Gregorabc563f2010-07-19 21:46:24 +00001847ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001848 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001849 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001850 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001851 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001852 TranslationUnitKind TUKind,
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00001853 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001854 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001855 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001856 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001857 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001858 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001859 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001860 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001861 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001862 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001863 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001864
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001865 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001866 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1867 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001868 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1869 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001870 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001871
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001872 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001873}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001874
1875ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1876 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001877 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001878 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001879 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001880 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001881 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001882 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001883 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001884 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001885 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001886 bool CacheCodeCompletionResults,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001887 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001888 bool SkipFunctionBodies,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001889 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001890 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001891 // No diagnostics engine was provided, so create our own diagnostics object
1892 // with the default options.
1893 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001894 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1895 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001896 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001897
Chris Lattner5f9e2722011-07-23 10:55:15 +00001898 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001899
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001900 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001901
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001902 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001903
Douglas Gregore47be3e2010-11-11 00:39:14 +00001904 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001905 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001906
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001907 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001908 llvm::makeArrayRef(ArgBegin, ArgEnd),
1909 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001910 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001911 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001912 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001913
Douglas Gregor4db64a42010-01-23 00:14:00 +00001914 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001915 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1916 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1917 if (const llvm::MemoryBuffer *
1918 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1919 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1920 } else {
1921 const char *fname = fileOrBuf.get<const char *>();
1922 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1923 }
1924 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001925 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1926 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1927 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001928
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001929 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001930 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001931
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001932 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1933
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001934 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001935 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001936 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001937 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001938 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001939 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001940 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001941 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001942 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001943 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001944 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1946 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001947 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001948 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001949 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001950
1951 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001952 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1953 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001954
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001955 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1956 // Some error occurred, if caller wants to examine diagnostics, pass it the
1957 // ASTUnit.
1958 if (ErrAST) {
1959 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1960 ErrAST->swap(AST);
1961 }
1962 return 0;
1963 }
1964
1965 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001966}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001967
1968bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001969 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001970 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001971
1972 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001973
Douglas Gregor213f18b2010-10-28 15:44:59 +00001974 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001975 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001976
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001977 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001978 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001979 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001980 for (PreprocessorOptions::remapped_file_buffer_iterator
1981 R = PPOpts.remapped_file_buffer_begin(),
1982 REnd = PPOpts.remapped_file_buffer_end();
1983 R != REnd;
1984 ++R) {
1985 delete R->second;
1986 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001987 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001988 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1989 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1990 if (const llvm::MemoryBuffer *
1991 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1992 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1993 memBuf);
1994 } else {
1995 const char *fname = fileOrBuf.get<const char *>();
1996 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1997 fname);
1998 }
1999 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002000
Douglas Gregoreababfb2010-08-04 05:53:38 +00002001 // If we have a preamble file lying around, or if we might try to
2002 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002003 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002004 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002005 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002006
Douglas Gregorabc563f2010-07-19 21:46:24 +00002007 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002008 getDiagnostics().Reset();
2009 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002010 if (OverrideMainBuffer)
2011 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002012
Douglas Gregor175c4a92010-07-23 23:58:40 +00002013 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002014 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002015
2016 // If we're caching global code-completion results, and the top-level
2017 // declarations have changed, clear out the code-completion cache.
2018 if (!Result && ShouldCacheCodeCompletionResults &&
2019 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2020 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002021
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002022 // We now need to clear out the completion info related to this translation
2023 // unit; it'll be recreated if necessary.
2024 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002025
Douglas Gregor175c4a92010-07-23 23:58:40 +00002026 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002027}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002028
Douglas Gregor87c08a52010-08-13 22:48:40 +00002029//----------------------------------------------------------------------------//
2030// Code completion
2031//----------------------------------------------------------------------------//
2032
2033namespace {
2034 /// \brief Code completion consumer that combines the cached code-completion
2035 /// results from an ASTUnit with the code-completion results provided to it,
2036 /// then passes the result on to
2037 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002038 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002039 ASTUnit &AST;
2040 CodeCompleteConsumer &Next;
2041
2042 public:
2043 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00002044 bool IncludeMacros, bool IncludeCodePatterns,
2045 bool IncludeGlobals)
2046 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002047 Next.isOutputBinary()), AST(AST), Next(Next)
2048 {
2049 // Compute the set of contexts in which we will look when we don't have
2050 // any information about the specific context.
2051 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002052 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2053 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2054 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2055 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2056 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2057 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2058 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2059 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2060 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2061 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2062 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2063 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2064 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002065
David Blaikie4e4d0842012-03-11 07:00:24 +00002066 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002067 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2068 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2069 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002070 }
2071
2072 virtual void ProcessCodeCompleteResults(Sema &S,
2073 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002074 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002075 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002076
2077 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2078 OverloadCandidate *Candidates,
2079 unsigned NumCandidates) {
2080 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2081 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002082
Douglas Gregordae68752011-02-01 22:57:45 +00002083 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002084 return Next.getAllocator();
2085 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002086
2087 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2088 return Next.getCodeCompletionTUInfo();
2089 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002090 };
2091}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002092
Douglas Gregor5f808c22010-08-16 21:18:39 +00002093/// \brief Helper function that computes which global names are hidden by the
2094/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002095static void CalculateHiddenNames(const CodeCompletionContext &Context,
2096 CodeCompletionResult *Results,
2097 unsigned NumResults,
2098 ASTContext &Ctx,
2099 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002100 bool OnlyTagNames = false;
2101 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002102 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002103 case CodeCompletionContext::CCC_TopLevel:
2104 case CodeCompletionContext::CCC_ObjCInterface:
2105 case CodeCompletionContext::CCC_ObjCImplementation:
2106 case CodeCompletionContext::CCC_ObjCIvarList:
2107 case CodeCompletionContext::CCC_ClassStructUnion:
2108 case CodeCompletionContext::CCC_Statement:
2109 case CodeCompletionContext::CCC_Expression:
2110 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002111 case CodeCompletionContext::CCC_DotMemberAccess:
2112 case CodeCompletionContext::CCC_ArrowMemberAccess:
2113 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002114 case CodeCompletionContext::CCC_Namespace:
2115 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002116 case CodeCompletionContext::CCC_Name:
2117 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002118 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002119 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002120 break;
2121
2122 case CodeCompletionContext::CCC_EnumTag:
2123 case CodeCompletionContext::CCC_UnionTag:
2124 case CodeCompletionContext::CCC_ClassOrStructTag:
2125 OnlyTagNames = true;
2126 break;
2127
2128 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002129 case CodeCompletionContext::CCC_MacroName:
2130 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002131 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002132 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002133 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002134 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002135 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002136 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002137 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002138 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2139 case CodeCompletionContext::CCC_ObjCClassMessage:
2140 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002141 // We're looking for nothing, or we're looking for names that cannot
2142 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002143 return;
2144 }
2145
John McCall0a2c5e22010-08-25 06:19:51 +00002146 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002147 for (unsigned I = 0; I != NumResults; ++I) {
2148 if (Results[I].Kind != Result::RK_Declaration)
2149 continue;
2150
2151 unsigned IDNS
2152 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2153
2154 bool Hiding = false;
2155 if (OnlyTagNames)
2156 Hiding = (IDNS & Decl::IDNS_Tag);
2157 else {
2158 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002159 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2160 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002161 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002162 HiddenIDNS |= Decl::IDNS_Tag;
2163 Hiding = (IDNS & HiddenIDNS);
2164 }
2165
2166 if (!Hiding)
2167 continue;
2168
2169 DeclarationName Name = Results[I].Declaration->getDeclName();
2170 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2171 HiddenNames.insert(Identifier->getName());
2172 else
2173 HiddenNames.insert(Name.getAsString());
2174 }
2175}
2176
2177
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002178void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2179 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002180 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002181 unsigned NumResults) {
2182 // Merge the results we were given with the results we cached.
2183 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002184 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002185 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002186 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002188 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002189 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002190 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002191 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002192 C = AST.cached_completion_begin(),
2193 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002194 C != CEnd; ++C) {
2195 // If the context we are in matches any of the contexts we are
2196 // interested in, we'll add this result.
2197 if ((C->ShowInContexts & InContexts) == 0)
2198 continue;
2199
2200 // If we haven't added any results previously, do so now.
2201 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002202 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2203 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002204 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2205 AddedResult = true;
2206 }
2207
Douglas Gregor5f808c22010-08-16 21:18:39 +00002208 // Determine whether this global completion result is hidden by a local
2209 // completion result. If so, skip it.
2210 if (C->Kind != CXCursor_MacroDefinition &&
2211 HiddenNames.count(C->Completion->getTypedText()))
2212 continue;
2213
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002214 // Adjust priority based on similar type classes.
2215 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002216 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002217 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002218 if (!Context.getPreferredType().isNull()) {
2219 if (C->Kind == CXCursor_MacroDefinition) {
2220 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002221 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002222 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002223 } else if (C->Type) {
2224 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002225 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002226 Context.getPreferredType().getUnqualifiedType());
2227 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2228 if (ExpectedSTC == C->TypeClass) {
2229 // We know this type is similar; check for an exact match.
2230 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002231 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002232 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002233 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002234 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2235 Priority /= CCF_ExactTypeMatch;
2236 else
2237 Priority /= CCF_SimilarTypeMatch;
2238 }
2239 }
2240 }
2241
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002242 // Adjust the completion string, if required.
2243 if (C->Kind == CXCursor_MacroDefinition &&
2244 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2245 // Create a new code-completion string that just contains the
2246 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002247 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2248 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002249 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002250 CursorKind = CXCursor_NotImplemented;
2251 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002252 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002253 }
2254
Douglas Gregor4125c372010-08-25 18:03:13 +00002255 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002256 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002257 }
2258
2259 // If we did not add any cached completion results, just forward the
2260 // results we were given to the next consumer.
2261 if (!AddedResult) {
2262 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2263 return;
2264 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002265
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002266 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2267 AllResults.size());
2268}
2269
2270
2271
Chris Lattner5f9e2722011-07-23 10:55:15 +00002272void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002273 RemappedFile *RemappedFiles,
2274 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002275 bool IncludeMacros,
2276 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002277 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002278 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002279 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002280 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2281 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002282 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002283 return;
2284
Douglas Gregor213f18b2010-10-28 15:44:59 +00002285 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002286 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002287 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002288
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002289 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002290 CCInvocation(new CompilerInvocation(*Invocation));
2291
2292 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2293 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002294
Douglas Gregor87c08a52010-08-13 22:48:40 +00002295 FrontendOpts.ShowMacrosInCodeCompletion
2296 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002297 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002298 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2299 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002300 FrontendOpts.CodeCompletionAt.FileName = File;
2301 FrontendOpts.CodeCompletionAt.Line = Line;
2302 FrontendOpts.CodeCompletionAt.Column = Column;
2303
2304 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002305 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002306
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002307 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002308
2309 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002310 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2311 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002312
Ted Kremenek4f327862011-03-21 18:40:17 +00002313 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002314 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315
2316 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002317 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002318 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002319 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002320 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002321 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002322
2323 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002324 Clang->getTargetOpts().Features = TargetFeatures;
2325 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2326 Clang->getTargetOpts()));
2327 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002328 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002329 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002330 }
2331
2332 // Inform the target of the language options.
2333 //
2334 // FIXME: We shouldn't need to do this, the target should be immutable once
2335 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002336 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002337
Ted Kremenek03201fb2011-03-21 18:40:07 +00002338 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002339 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002340 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002342 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002343 "IR inputs not support here!");
2344
2345
2346 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002347 Clang->setFileManager(&FileMgr);
2348 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002349
2350 // Remap files.
2351 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002352 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002353 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002354 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2355 if (const llvm::MemoryBuffer *
2356 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2357 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2358 OwnedBuffers.push_back(memBuf);
2359 } else {
2360 const char *fname = fileOrBuf.get<const char *>();
2361 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2362 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002363 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002364
Douglas Gregor87c08a52010-08-13 22:48:40 +00002365 // Use the code completion consumer we were given, but adding any cached
2366 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002367 AugmentedCodeCompleteConsumer *AugmentedConsumer
2368 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2369 FrontendOpts.ShowMacrosInCodeCompletion,
2370 FrontendOpts.ShowCodePatternsInCodeCompletion,
2371 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002372 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002373
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002374 Clang->getFrontendOpts().SkipFunctionBodies = true;
2375
Douglas Gregordf95a132010-08-09 20:45:32 +00002376 // If we have a precompiled preamble, try to use it. We only allow
2377 // the use of the precompiled preamble if we're if the completion
2378 // point is within the main file, after the end of the precompiled
2379 // preamble.
2380 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002381 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002382 using llvm::sys::FileStatus;
2383 llvm::sys::PathWithStatus CompleteFilePath(File);
2384 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2385 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2386 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002387 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2388 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002389 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002390 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002391 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002392 }
2393
2394 // If the main file has been overridden due to the use of a preamble,
2395 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002396 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002397 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002398 stored_diag_begin(),
2399 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002400 if (OverrideMainBuffer) {
2401 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2402 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2403 PreprocessorOpts.PrecompiledPreambleBytes.second
2404 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002405 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002406 PreprocessorOpts.DisablePCHValidation = true;
2407
Douglas Gregor2283d792010-08-20 00:59:43 +00002408 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002409 } else {
2410 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2411 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002412 }
2413
Douglas Gregordca8ee82011-05-06 16:33:08 +00002414 // Disable the preprocessing record
2415 PreprocessorOpts.DetailedRecord = false;
2416
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002417 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002419 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002420 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002421 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002422 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2423 getSourceManager(), PreambleDiagnostics,
2424 StoredDiagnostics);
2425 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002426 Act->Execute();
2427 Act->EndSourceFile();
2428 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002429
2430 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002431}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002432
Chris Lattner5f9e2722011-07-23 10:55:15 +00002433CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002434 // Write to a temporary file and later rename it to the actual file, to avoid
2435 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002436 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002437 TempPath = File;
2438 TempPath += "-%%%%%%%%";
2439 int fd;
2440 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2441 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002442 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002443
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002444 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2445 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002446 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002447
2448 serialize(Out);
2449 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002450 if (Out.has_error()) {
2451 Out.clear_error();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002452 return CXSaveError_Unknown;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002453 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002454
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002455 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002456 bool exists;
2457 llvm::sys::fs::remove(TempPath.str(), exists);
2458 return CXSaveError_Unknown;
2459 }
2460
2461 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002462}
2463
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002465 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002466
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002467 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002468 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002469 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002470 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002471 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002472
2473 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002474 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002475 OS.write((char *)&Buffer.front(), Buffer.size());
2476
2477 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002478}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002479
2480typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2481
2482static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2483 unsigned Raw = L.getRawEncoding();
2484 const unsigned MacroBit = 1U << 31;
2485 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2486 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2487}
2488
2489void ASTUnit::TranslateStoredDiagnostics(
2490 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002491 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002492 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002493 const SmallVectorImpl<StoredDiagnostic> &Diags,
2494 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002495 // The stored diagnostic has the old source manager in it; update
2496 // the locations to refer into the new source manager. We also need to remap
2497 // all the locations to the new view. This includes the diag location, any
2498 // associated source ranges, and the source ranges of associated fix-its.
2499 // FIXME: There should be a cleaner way to do this.
2500
Chris Lattner5f9e2722011-07-23 10:55:15 +00002501 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002502 Result.reserve(Diags.size());
2503 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002504 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002505 assert(Mod && "Don't have preamble module");
2506 SLocRemap &Remap = Mod->SLocRemap;
2507 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2508 // Rebuild the StoredDiagnostic.
2509 const StoredDiagnostic &SD = Diags[I];
2510 SourceLocation L = SD.getLocation();
2511 TranslateSLoc(L, Remap);
2512 FullSourceLoc Loc(L, SrcMgr);
2513
Chris Lattner5f9e2722011-07-23 10:55:15 +00002514 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002515 Ranges.reserve(SD.range_size());
2516 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2517 E = SD.range_end();
2518 I != E; ++I) {
2519 SourceLocation BL = I->getBegin();
2520 TranslateSLoc(BL, Remap);
2521 SourceLocation EL = I->getEnd();
2522 TranslateSLoc(EL, Remap);
2523 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2524 }
2525
Chris Lattner5f9e2722011-07-23 10:55:15 +00002526 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002527 FixIts.reserve(SD.fixit_size());
2528 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2529 E = SD.fixit_end();
2530 I != E; ++I) {
2531 FixIts.push_back(FixItHint());
2532 FixItHint &FH = FixIts.back();
2533 FH.CodeToInsert = I->CodeToInsert;
2534 SourceLocation BL = I->RemoveRange.getBegin();
2535 TranslateSLoc(BL, Remap);
2536 SourceLocation EL = I->RemoveRange.getEnd();
2537 TranslateSLoc(EL, Remap);
2538 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2539 I->RemoveRange.isTokenRange());
2540 }
2541
2542 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2543 SD.getMessage(), Loc, Ranges, FixIts));
2544 }
2545 Result.swap(Out);
2546}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002547
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002548static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2549 std::pair<unsigned, Decl *> R) {
2550 return L.first < R.first;
2551}
2552
2553void ASTUnit::addFileLevelDecl(Decl *D) {
2554 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002555
2556 // We only care about local declarations.
2557 if (D->isFromASTFile())
2558 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002559
2560 SourceManager &SM = *SourceMgr;
2561 SourceLocation Loc = D->getLocation();
2562 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2563 return;
2564
2565 // We only keep track of the file-level declarations of each file.
2566 if (!D->getLexicalDeclContext()->isFileContext())
2567 return;
2568
2569 SourceLocation FileLoc = SM.getFileLoc(Loc);
2570 assert(SM.isLocalSourceLocation(FileLoc));
2571 FileID FID;
2572 unsigned Offset;
2573 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2574 if (FID.isInvalid())
2575 return;
2576
2577 LocDeclsTy *&Decls = FileDecls[FID];
2578 if (!Decls)
2579 Decls = new LocDeclsTy();
2580
2581 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2582
2583 if (Decls->empty() || Decls->back().first <= Offset) {
2584 Decls->push_back(LocDecl);
2585 return;
2586 }
2587
2588 LocDeclsTy::iterator
2589 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2590
2591 Decls->insert(I, LocDecl);
2592}
2593
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002594void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2595 SmallVectorImpl<Decl *> &Decls) {
2596 if (File.isInvalid())
2597 return;
2598
2599 if (SourceMgr->isLoadedFileID(File)) {
2600 assert(Ctx->getExternalSource() && "No external source!");
2601 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2602 Decls);
2603 }
2604
2605 FileDeclsTy::iterator I = FileDecls.find(File);
2606 if (I == FileDecls.end())
2607 return;
2608
2609 LocDeclsTy &LocDecls = *I->second;
2610 if (LocDecls.empty())
2611 return;
2612
2613 LocDeclsTy::iterator
2614 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2615 std::make_pair(Offset, (Decl*)0), compLocDecl);
2616 if (BeginIt != LocDecls.begin())
2617 --BeginIt;
2618
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002619 // If we are pointing at a top-level decl inside an objc container, we need
2620 // to backtrack until we find it otherwise we will fail to report that the
2621 // region overlaps with an objc container.
2622 while (BeginIt != LocDecls.begin() &&
2623 BeginIt->second->isTopLevelDeclInObjCContainer())
2624 --BeginIt;
2625
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002626 LocDeclsTy::iterator
2627 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2628 std::make_pair(Offset+Length, (Decl*)0),
2629 compLocDecl);
2630 if (EndIt != LocDecls.end())
2631 ++EndIt;
2632
2633 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2634 Decls.push_back(DIt->second);
2635}
2636
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002637SourceLocation ASTUnit::getLocation(const FileEntry *File,
2638 unsigned Line, unsigned Col) const {
2639 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002640 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002641 return SM.getMacroArgExpandedLocation(Loc);
2642}
2643
2644SourceLocation ASTUnit::getLocation(const FileEntry *File,
2645 unsigned Offset) const {
2646 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002647 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002648 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2649}
2650
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002651/// \brief If \arg Loc is a loaded location from the preamble, returns
2652/// the corresponding local location of the main file, otherwise it returns
2653/// \arg Loc.
2654SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2655 FileID PreambleID;
2656 if (SourceMgr)
2657 PreambleID = SourceMgr->getPreambleFileID();
2658
2659 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2660 return Loc;
2661
2662 unsigned Offs;
2663 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2664 SourceLocation FileLoc
2665 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2666 return FileLoc.getLocWithOffset(Offs);
2667 }
2668
2669 return Loc;
2670}
2671
2672/// \brief If \arg Loc is a local location of the main file but inside the
2673/// preamble chunk, returns the corresponding loaded location from the
2674/// preamble, otherwise it returns \arg Loc.
2675SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2676 FileID PreambleID;
2677 if (SourceMgr)
2678 PreambleID = SourceMgr->getPreambleFileID();
2679
2680 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2681 return Loc;
2682
2683 unsigned Offs;
2684 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2685 Offs < Preamble.size()) {
2686 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2687 return FileLoc.getLocWithOffset(Offs);
2688 }
2689
2690 return Loc;
2691}
2692
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002693bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2694 FileID FID;
2695 if (SourceMgr)
2696 FID = SourceMgr->getPreambleFileID();
2697
2698 if (Loc.isInvalid() || FID.isInvalid())
2699 return false;
2700
2701 return SourceMgr->isInFileID(Loc, FID);
2702}
2703
2704bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2705 FileID FID;
2706 if (SourceMgr)
2707 FID = SourceMgr->getMainFileID();
2708
2709 if (Loc.isInvalid() || FID.isInvalid())
2710 return false;
2711
2712 return SourceMgr->isInFileID(Loc, FID);
2713}
2714
2715SourceLocation ASTUnit::getEndOfPreambleFileID() {
2716 FileID FID;
2717 if (SourceMgr)
2718 FID = SourceMgr->getPreambleFileID();
2719
2720 if (FID.isInvalid())
2721 return SourceLocation();
2722
2723 return SourceMgr->getLocForEndOfFile(FID);
2724}
2725
2726SourceLocation ASTUnit::getStartOfMainFileID() {
2727 FileID FID;
2728 if (SourceMgr)
2729 FID = SourceMgr->getMainFileID();
2730
2731 if (FID.isInvalid())
2732 return SourceLocation();
2733
2734 return SourceMgr->getLocForStartOfFile(FID);
2735}
2736
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002737void ASTUnit::PreambleData::countLines() const {
2738 NumLines = 0;
2739 if (empty())
2740 return;
2741
2742 for (std::vector<char>::const_iterator
2743 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2744 if (*I == '\n')
2745 ++NumLines;
2746 }
2747 if (Buffer.back() != '\n')
2748 ++NumLines;
2749}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002750
2751#ifndef NDEBUG
2752ASTUnit::ConcurrencyState::ConcurrencyState() {
2753 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2754}
2755
2756ASTUnit::ConcurrencyState::~ConcurrencyState() {
2757 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2758}
2759
2760void ASTUnit::ConcurrencyState::start() {
2761 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2762 assert(acquired && "Concurrent access to ASTUnit!");
2763}
2764
2765void ASTUnit::ConcurrencyState::finish() {
2766 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2767}
2768
2769#else // NDEBUG
2770
2771ASTUnit::ConcurrencyState::ConcurrencyState() {}
2772ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2773void ASTUnit::ConcurrencyState::start() {}
2774void ASTUnit::ConcurrencyState::finish() {}
2775
2776#endif