blob: 15500989e87f89c268d2de3eca1b343202e2f5d1 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000030#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000031#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000049#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000050#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000051#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000052#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000053#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000054#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000055using namespace clang;
56
Douglas Gregor213f18b2010-10-28 15:44:59 +000057using llvm::TimeRecord;
58
59namespace {
60 class SimpleTimer {
61 bool WantTiming;
62 TimeRecord Start;
63 std::string Output;
64
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000066 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Chris Lattner5f9e2722011-07-23 10:55:15 +000071 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000073 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000074 }
75
Douglas Gregor213f18b2010-10-28 15:44:59 +000076 ~SimpleTimer() {
77 if (WantTiming) {
78 TimeRecord Elapsed = TimeRecord::getCurrentTime();
79 Elapsed -= Start;
80 llvm::errs() << Output << ':';
81 Elapsed.print(Elapsed, llvm::errs());
82 llvm::errs() << '\n';
83 }
84 }
85 };
Ted Kremenek1872b312011-10-27 17:55:18 +000086
87 struct OnDiskData {
88 /// \brief The file in which the precompiled preamble is stored.
89 std::string PreambleFile;
90
91 /// \brief Temporary files that should be removed when the ASTUnit is
92 /// destroyed.
93 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
94
95 /// \brief Erase temporary files.
96 void CleanTemporaryFiles();
97
98 /// \brief Erase the preamble file.
99 void CleanPreambleFile();
100
101 /// \brief Erase temporary files and the preamble file.
102 void Cleanup();
103 };
104}
105
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000106static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
107 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
108 return M;
109}
110
Ted Kremenek1872b312011-10-27 17:55:18 +0000111static void cleanupOnDiskMapAtExit(void);
112
113typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
114static OnDiskDataMap &getOnDiskDataMap() {
115 static OnDiskDataMap M;
116 static bool hasRegisteredAtExit = false;
117 if (!hasRegisteredAtExit) {
118 hasRegisteredAtExit = true;
119 atexit(cleanupOnDiskMapAtExit);
120 }
121 return M;
122}
123
124static void cleanupOnDiskMapAtExit(void) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000125 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000126 OnDiskDataMap &M = getOnDiskDataMap();
127 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
128 // We don't worry about freeing the memory associated with OnDiskDataMap.
129 // All we care about is erasing stale files.
130 I->second->Cleanup();
131 }
132}
133
134static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000135 // We require the mutex since we are modifying the structure of the
136 // DenseMap.
137 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000138 OnDiskDataMap &M = getOnDiskDataMap();
139 OnDiskData *&D = M[AU];
140 if (!D)
141 D = new OnDiskData();
142 return *D;
143}
144
145static void erasePreambleFile(const ASTUnit *AU) {
146 getOnDiskData(AU).CleanPreambleFile();
147}
148
149static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000150 // We require the mutex since we are modifying the structure of the
151 // DenseMap.
152 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000153 OnDiskDataMap &M = getOnDiskDataMap();
154 OnDiskDataMap::iterator I = M.find(AU);
155 if (I != M.end()) {
156 I->second->Cleanup();
157 delete I->second;
158 M.erase(AU);
159 }
160}
161
162static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
163 getOnDiskData(AU).PreambleFile = preambleFile;
164}
165
166static const std::string &getPreambleFile(const ASTUnit *AU) {
167 return getOnDiskData(AU).PreambleFile;
168}
169
170void OnDiskData::CleanTemporaryFiles() {
171 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
172 TemporaryFiles[I].eraseFromDisk();
173 TemporaryFiles.clear();
174}
175
176void OnDiskData::CleanPreambleFile() {
177 if (!PreambleFile.empty()) {
178 llvm::sys::Path(PreambleFile).eraseFromDisk();
179 PreambleFile.clear();
180 }
181}
182
183void OnDiskData::Cleanup() {
184 CleanTemporaryFiles();
185 CleanPreambleFile();
186}
187
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000188void ASTUnit::clearFileLevelDecls() {
189 for (FileDeclsTy::iterator
190 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
191 delete I->second;
192 FileDecls.clear();
193}
194
Ted Kremenek1872b312011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
199void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000201}
202
Douglas Gregoreababfb2010-08-04 05:53:38 +0000203/// \brief After failing to build a precompiled preamble (due to
204/// errors in the source that occurs in the preamble), the number of
205/// reparses during which we'll skip even trying to precompile the
206/// preamble.
207const unsigned DefaultPreambleRebuildInterval = 5;
208
Douglas Gregore3c60a72010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000212static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000215 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000216 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000217 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000218 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000219 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000220 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000221 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000222 ShouldCacheCodeCompletionResults(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000223 CompletionCacheTopLevelHashValue(0),
224 PreambleTopLevelHashValue(0),
225 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000226 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000227 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000228 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000229 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
230 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000231}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000232
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek1872b312011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000243 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (PreprocessorOptions::remapped_file_buffer_iterator
246 FB = PPOpts.remapped_file_buffer_begin(),
247 FBEnd = PPOpts.remapped_file_buffer_end();
248 FB != FBEnd;
249 ++FB)
250 delete FB->second;
251 }
Douglas Gregor28233422010-07-27 14:52:07 +0000252
253 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000254 delete PreambleBuffer;
255
Douglas Gregor213f18b2010-10-28 15:44:59 +0000256 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000257
258 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000259 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000260 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
261 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor8071e422010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
268static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
278 unsigned Contexts = 0;
279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
283 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000287 | (1 << (CodeCompletionContext::CCC_Type - 1))
288 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
292 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000301 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
305 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
306
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000308 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000310 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
311 if (Record->isUnion())
312 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
313 else
314 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
315
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
322 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
323 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000324 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
326 } else if (isa<ObjCProtocolDecl>(ND)) {
327 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
329 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregor87c08a52010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor213f18b2010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000354 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
355 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000358 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
359
Douglas Gregor87c08a52010-08-13 22:48:40 +0000360 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
361 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000363 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000364 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000365 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000366 *CachedCompletionAllocator,
367 getCodeCompletionTUInfo());
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000369 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000370 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000371 CachedResult.Priority = Results[I].Priority;
372 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000373 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000374
Douglas Gregorf5586f62010-08-16 18:08:11 +0000375 // Keep track of the type of this completion in an ASTContext-agnostic
376 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000377 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000378 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000379 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000380 CachedResult.Type = 0;
381 } else {
382 CanQualType CanUsageType
383 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
384 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
385
386 // Determine whether we have already seen this type. If so, we save
387 // ourselves the work of formatting the type string by using the
388 // temporary, CanQualType-based hash table to find the associated value.
389 unsigned &TypeValue = CompletionTypes[CanUsageType];
390 if (TypeValue == 0) {
391 TypeValue = CompletionTypes.size();
392 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
393 = TypeValue;
394 }
395
396 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000397 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000398
Douglas Gregor8071e422010-08-15 06:18:01 +0000399 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000400
401 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000402 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000403 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
404 // The contexts in which a nested-name-specifier can appear in C++.
405 unsigned NNSContexts
406 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
407 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
408 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
409 | (1 << (CodeCompletionContext::CCC_Statement - 1))
410 | (1 << (CodeCompletionContext::CCC_Expression - 1))
411 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
412 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
413 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
414 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000415 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000416 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
417 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000418
419 if (isa<NamespaceDecl>(Results[I].Declaration) ||
420 isa<NamespaceAliasDecl>(Results[I].Declaration))
421 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
422
423 if (unsigned RemainingContexts
424 = NNSContexts & ~CachedResult.ShowInContexts) {
425 // If there any contexts where this completion can be a
426 // nested-name-specifier but isn't already an option, create a
427 // nested-name-specifier completion.
428 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000429 CachedResult.Completion
430 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000431 *CachedCompletionAllocator,
432 getCodeCompletionTUInfo());
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
438 }
439 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000440 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000441 }
442
Douglas Gregor87c08a52010-08-13 22:48:40 +0000443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
447 break;
448
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000451 CachedResult.Completion
452 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000453 *CachedCompletionAllocator,
454 getCodeCompletionTUInfo());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000455 CachedResult.ShowInContexts
456 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
457 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
458 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
459 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
460 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
461 | (1 << (CodeCompletionContext::CCC_Statement - 1))
462 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000463 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000464 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000465 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000466 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
467 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000468
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedResult.Priority = Results[I].Priority;
470 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000471 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000472 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000473 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000474 CachedCompletionResults.push_back(CachedResult);
475 break;
476 }
477 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000479
480 // Save the current top-level hash value.
481 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482}
483
484void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000486 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000487 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000488}
489
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000490namespace {
491
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000492/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000493/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000494class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000495 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000496 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497 LangOptions &LangOpt;
498 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000499 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500 std::string &Predefines;
501 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000503 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000505 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000507 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
508 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000509 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000510 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000513 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000514 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000517 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000518 return false;
519
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000521
522 // Initialize the preprocessor.
523 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000524
525 // Initialize the ASTContext
526 Context.InitBuiltinTypes(*Target);
527
528 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000529 return false;
530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chris Lattner5f9e2722011-07-23 10:55:15 +0000532 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000533 // If we've already initialized the target, don't do it again.
534 if (Target)
535 return false;
536
537 // FIXME: This is broken, we should store the TargetOptions in the AST file.
538 TargetOptions TargetOpts;
539 TargetOpts.ABI = "";
540 TargetOpts.CXXABI = "";
541 TargetOpts.CPU = "";
542 TargetOpts.Features.clear();
543 TargetOpts.Triple = Triple;
544 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000545 return false;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000548 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000549 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000550 std::string &SuggestedPredefines,
551 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000552 Predefines = Buffers[0].Data;
553 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
554 Predefines += Buffers[I].Data;
555 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 return false;
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000559 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000560 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000563 virtual void ReadCounter(unsigned Value) {
564 Counter = Value;
565 }
566};
567
David Blaikie26e7a902011-09-26 00:01:39 +0000568class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000569 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000570
571public:
David Blaikie26e7a902011-09-26 00:01:39 +0000572 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000573 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000574 : StoredDiags(StoredDiags) { }
575
David Blaikied6471f72011-09-25 23:23:43 +0000576 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000577 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000578
579 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
580 // Just drop any diagnostics that come from cloned consumers; they'll
581 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000582 // FIXME: We'd like to be able to capture these somehow, even if it's just
583 // file/line/column, because they could occur when parsing module maps or
584 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000585 return new IgnoringDiagConsumer();
586 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000587};
588
589/// \brief RAII object that optionally captures diagnostics, if
590/// there is no diagnostic client to capture them already.
591class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000592 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000593 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000594 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000595
596public:
David Blaikied6471f72011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000599 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000600 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000601 if (RequestCapture || Diags.getClient() == 0) {
602 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000603 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000604 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000605 }
606
607 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000608 if (Diags.getClient() == &Client) {
609 Diags.takeClient();
610 Diags.setClient(PreviousClient);
611 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000615} // anonymous namespace
616
David Blaikie26e7a902011-09-26 00:01:39 +0000617void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000618 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000619 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000620 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000621
Douglas Gregora88084b2010-02-18 18:08:43 +0000622 StoredDiags.push_back(StoredDiagnostic(Level, Info));
623}
624
Steve Naroff77accc12009-09-03 18:19:54 +0000625const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000626 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000627}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000628
Chris Lattner5f9e2722011-07-23 10:55:15 +0000629llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000630 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000631 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000632 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000633}
634
Douglas Gregore47be3e2010-11-11 00:39:14 +0000635/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000636void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000637 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000638 ASTUnit &AST, bool CaptureDiagnostics) {
639 if (!Diags.getPtr()) {
640 // No diagnostics engine was provided, so create our own diagnostics object
641 // with the default options.
642 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000643 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000644 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000645 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000646 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
647 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000648 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000650 }
651}
652
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000653ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000655 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000656 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000657 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000658 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000659 bool CaptureDiagnostics,
660 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000661 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000662
663 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000664 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
665 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000666 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
667 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000668 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000669
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000670 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000671
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000672 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000673 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000674 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000675 AST->FileMgr = new FileManager(FileSystemOpts);
676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
677 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000678 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000679 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000680 AST->ASTFileLangOpts,
681 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000682
Douglas Gregor4db64a42010-01-23 00:14:00 +0000683 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000684 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
685 if (const llvm::MemoryBuffer *
686 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
687 // Create the file entry for the file that we're mapping from.
688 const FileEntry *FromFile
689 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
690 memBuf->getBufferSize(),
691 0);
692 if (!FromFile) {
693 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
694 << RemappedFiles[I].first;
695 delete memBuf;
696 continue;
697 }
698
699 // Override the contents of the "from" file with the contents of
700 // the "to" file.
701 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
702
703 } else {
704 const char *fname = fileOrBuf.get<const char *>();
705 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
706 if (!ToFile) {
707 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
708 << RemappedFiles[I].first << fname;
709 continue;
710 }
711
712 // Create the file entry for the file that we're mapping from.
713 const FileEntry *FromFile
714 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
715 ToFile->getSize(),
716 0);
717 if (!FromFile) {
718 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
719 << RemappedFiles[I].first;
720 delete memBuf;
721 continue;
722 }
723
724 // Override the contents of the "from" file with the contents of
725 // the "to" file.
726 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000727 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000728 }
729
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000730 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000732 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000733 std::string Predefines;
734 unsigned Counter;
735
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000736 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000737
Douglas Gregor998b3d32011-09-01 23:39:15 +0000738 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
739 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
740 *AST,
741 /*IILookup=*/0,
742 /*OwnsHeaderSearch=*/false,
743 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000744 Preprocessor &PP = *AST->PP;
745
746 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
747 AST->getSourceManager(),
748 /*Target=*/0,
749 PP.getIdentifierTable(),
750 PP.getSelectorTable(),
751 PP.getBuiltinInfo(),
752 /* size_reserve = */0,
753 /*DelayInitialization=*/true);
754 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000755
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000756 Reader.reset(new ASTReader(PP, Context,
757 /*isysroot=*/"",
758 /*DisableValidation=*/false,
759 /*DisableStatCache=*/false,
760 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000761
762 // Recover resources if we crash before exiting this method.
763 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
764 ReaderCleanup(Reader.get());
765
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000766 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000767 AST->ASTFileLangOpts, HeaderInfo,
768 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000769
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000770 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000771 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000774 case ASTReader::Failure:
775 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000776 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000777 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000780 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
781
Daniel Dunbard5b61262009-09-21 03:03:47 +0000782 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000783 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000785 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000786 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000787 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000788 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000789 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000790
791 // Unregister the cleanup for ASTReader. It will get cleaned up
792 // by the ASTUnit cleanup.
793 ReaderCleanup.unregister();
794
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000795 Context.setExternalSource(Source);
796
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000797 // Create an AST consumer, even though it isn't used.
798 AST->Consumer.reset(new ASTConsumer);
799
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000800 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000801 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
802 AST->TheSema->Initialize();
803 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000804 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000805
Mike Stump1eb44332009-09-09 15:08:12 +0000806 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000807}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000808
809namespace {
810
Douglas Gregor9b7db622011-02-16 18:16:54 +0000811/// \brief Preprocessor callback class that updates a hash value with the names
812/// of all macros that have been defined by the translation unit.
813class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
814 unsigned &Hash;
815
816public:
817 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
818
819 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
820 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
821 }
822};
823
824/// \brief Add the given declaration to the hash of all top-level entities.
825void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
826 if (!D)
827 return;
828
829 DeclContext *DC = D->getDeclContext();
830 if (!DC)
831 return;
832
833 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
834 return;
835
836 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
837 if (ND->getIdentifier())
838 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
839 else if (DeclarationName Name = ND->getDeclName()) {
840 std::string NameStr = Name.getAsString();
841 Hash = llvm::HashString(NameStr, Hash);
842 }
843 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000844 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000845}
846
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000847class TopLevelDeclTrackerConsumer : public ASTConsumer {
848 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000849 unsigned &Hash;
850
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000851public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000852 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
853 : Unit(_Unit), Hash(Hash) {
854 Hash = 0;
855 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000856
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000857 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000858 if (!D)
859 return;
860
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000861 // FIXME: Currently ObjC method declarations are incorrectly being
862 // reported as top-level declarations, even though their DeclContext
863 // is the containing ObjC @interface/@implementation. This is a
864 // fundamental problem in the parser right now.
865 if (isa<ObjCMethodDecl>(D))
866 return;
867
868 AddTopLevelDeclarationToHash(D, Hash);
869 Unit.addTopLevelDecl(D);
870
871 handleFileLevelDecl(D);
872 }
873
874 void handleFileLevelDecl(Decl *D) {
875 Unit.addFileLevelDecl(D);
876 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
877 for (NamespaceDecl::decl_iterator
878 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
879 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000880 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000881 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000882
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000883 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000884 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
885 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000886 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000887 }
888
Sebastian Redl27372b42010-08-11 18:52:41 +0000889 // We're not interested in "interesting" decls.
890 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000891
892 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
893 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
894 handleTopLevelDecl(*it);
895 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000896};
897
898class TopLevelDeclTrackerAction : public ASTFrontendAction {
899public:
900 ASTUnit &Unit;
901
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000902 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000903 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000904 CI.getPreprocessor().addPPCallbacks(
905 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
906 return new TopLevelDeclTrackerConsumer(Unit,
907 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000908 }
909
910public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
912
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000913 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000914 virtual TranslationUnitKind getTranslationUnitKind() {
915 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000916 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000917};
918
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000919class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000920 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000921 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000922 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000923
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000924public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000925 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000926 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000927 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000928 Hash(Unit.getCurrentTopLevelHashValue()) {
929 Hash = 0;
930 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000931
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000932 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000933 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
934 Decl *D = *it;
935 // FIXME: Currently ObjC method declarations are incorrectly being
936 // reported as top-level declarations, even though their DeclContext
937 // is the containing ObjC @interface/@implementation. This is a
938 // fundamental problem in the parser right now.
939 if (isa<ObjCMethodDecl>(D))
940 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000941 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000942 TopLevelDecls.push_back(D);
943 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000944 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000945 }
946
947 virtual void HandleTranslationUnit(ASTContext &Ctx) {
948 PCHGenerator::HandleTranslationUnit(Ctx);
949 if (!Unit.getDiagnostics().hasErrorOccurred()) {
950 // Translate the top-level declarations we captured during
951 // parsing into declaration IDs in the precompiled
952 // preamble. This will allow us to deserialize those top-level
953 // declarations when requested.
954 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
955 Unit.addTopLevelDeclFromPreamble(
956 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000957 }
958 }
959};
960
961class PrecompilePreambleAction : public ASTFrontendAction {
962 ASTUnit &Unit;
963
964public:
965 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
966
967 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000968 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000969 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000970 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000971 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000972 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
973 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000974 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000975 return 0;
976
Douglas Gregor832d6202011-07-22 16:35:34 +0000977 if (!CI.getFrontendOpts().RelocatablePCH)
978 Sysroot.clear();
979
Douglas Gregor9b7db622011-02-16 18:16:54 +0000980 CI.getPreprocessor().addPPCallbacks(
981 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000982 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
983 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000984 }
985
986 virtual bool hasCodeCompletionSupport() const { return false; }
987 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000988 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000989};
990
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000991}
992
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000993static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
994 StoredDiagnostics) {
995 // Get rid of stored diagnostics except the ones from the driver which do not
996 // have a source location.
997 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
998 if (StoredDiagnostics[I].getLocation().isValid()) {
999 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1000 --I;
1001 }
1002 }
1003}
1004
1005static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1006 StoredDiagnostics,
1007 SourceManager &SM) {
1008 // The stored diagnostic has the old source manager in it; update
1009 // the locations to refer into the new source manager. Since we've
1010 // been careful to make sure that the source manager's state
1011 // before and after are identical, so that we can reuse the source
1012 // location itself.
1013 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1014 if (StoredDiagnostics[I].getLocation().isValid()) {
1015 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1016 StoredDiagnostics[I].setLocation(Loc);
1017 }
1018 }
1019}
1020
Douglas Gregorabc563f2010-07-19 21:46:24 +00001021/// Parse the source file into a translation unit using the given compiler
1022/// invocation, replacing the current translation unit.
1023///
1024/// \returns True if a failure occurred that causes the ASTUnit not to
1025/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001026bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001027 delete SavedMainFileBuffer;
1028 SavedMainFileBuffer = 0;
1029
Ted Kremenek4f327862011-03-21 18:40:17 +00001030 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001031 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001032 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001033 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001034
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001035 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001036 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037
1038 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001039 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1040 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001041
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001042 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001043 CCInvocation(new CompilerInvocation(*Invocation));
1044
1045 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001046 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001047
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001048 // Set up diagnostics, capturing any diagnostics that would
1049 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001050 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001051
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001052 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001053 Clang->getTargetOpts().Features = TargetFeatures;
1054 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001055 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001056 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001057 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001058 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001059 }
1060
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001061 // Inform the target of the language options.
1062 //
1063 // FIXME: We shouldn't need to do this, the target should be immutable once
1064 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001065 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001066
Ted Kremenek03201fb2011-03-21 18:40:07 +00001067 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001068 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001069 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001070 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001071 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001072 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001073
Douglas Gregorabc563f2010-07-19 21:46:24 +00001074 // Configure the various subsystems.
1075 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001076 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001077 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001078 FileMgr = new FileManager(FileSystemOpts);
1079 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001080 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001081 Ctx = 0;
1082 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001083 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001084
1085 // Clear out old caches and data.
1086 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001087 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001089
Douglas Gregorf128fed2010-08-20 00:02:33 +00001090 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001091 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001092 TopLevelDeclsInPreamble.clear();
1093 }
1094
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001095 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001098 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001100
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001101 // If the main file has been overridden due to the use of a preamble,
1102 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001103 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001104 if (OverrideMainBuffer) {
1105 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1106 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1107 PreprocessorOpts.PrecompiledPreambleBytes.second
1108 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001109 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001110 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001111
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001112 // The stored diagnostic has the old source manager in it; update
1113 // the locations to refer into the new source manager. Since we've
1114 // been careful to make sure that the source manager's state
1115 // before and after are identical, so that we can reuse the source
1116 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001117 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001118
1119 // Keep track of the override buffer;
1120 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001121 }
1122
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001123 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001124 new TopLevelDeclTrackerAction(*this));
1125
1126 // Recover resources if we crash before exiting this method.
1127 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1128 ActCleanup(Act.get());
1129
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001130 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001131 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001132
1133 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001134 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001135 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1136 getSourceManager(), PreambleDiagnostics,
1137 StoredDiagnostics);
1138 }
1139
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001140 Act->Execute();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001141
1142 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001143
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001144 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001145
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001146 FailedParseDiagnostics.clear();
1147
Douglas Gregorabc563f2010-07-19 21:46:24 +00001148 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001149
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001150error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001152 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001153 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001154 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001155 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001156
1157 // Keep the ownership of the data in the ASTUnit because the client may
1158 // want to see the diagnostics.
1159 transferASTDataFromCompilerInstance(*Clang);
1160 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001161 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001162 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001163 return true;
1164}
1165
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166/// \brief Simple function to retrieve a path for a preamble precompiled header.
1167static std::string GetPreamblePCHPath() {
1168 // FIXME: This is lame; sys::Path should provide this function (in particular,
1169 // it should know how to find the temporary files dir).
1170 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001171 // FIXME: This is a hack so that we can override the preamble file during
1172 // crash-recovery testing, which is the only case where the preamble files
1173 // are not necessarily cleaned up.
1174 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1175 if (TmpFile)
1176 return TmpFile;
1177
Douglas Gregor44c181a2010-07-23 00:33:23 +00001178 std::string Error;
1179 const char *TmpDir = ::getenv("TMPDIR");
1180 if (!TmpDir)
1181 TmpDir = ::getenv("TEMP");
1182 if (!TmpDir)
1183 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001184#ifdef LLVM_ON_WIN32
1185 if (!TmpDir)
1186 TmpDir = ::getenv("USERPROFILE");
1187#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188 if (!TmpDir)
1189 TmpDir = "/tmp";
1190 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001191 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001193 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001194 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001195 return std::string();
1196
Douglas Gregor44c181a2010-07-23 00:33:23 +00001197 return P.str();
1198}
1199
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001200/// \brief Compute the preamble for the main file, providing the source buffer
1201/// that corresponds to the main file along with a pair (bytes, start-of-line)
1202/// that describes the preamble.
1203std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001204ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1205 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001206 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001207 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001208 CreatedBuffer = false;
1209
Douglas Gregor44c181a2010-07-23 00:33:23 +00001210 // Try to determine if the main file has been remapped, either from the
1211 // command line (to another file) or directly through the compiler invocation
1212 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001213 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001214 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001215 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1216 // Check whether there is a file-file remapping of the main file
1217 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001218 M = PreprocessorOpts.remapped_file_begin(),
1219 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 M != E;
1221 ++M) {
1222 llvm::sys::PathWithStatus MPath(M->first);
1223 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1224 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1225 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001226 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001227 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001228 CreatedBuffer = false;
1229 }
1230
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001231 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001232 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001233 return std::make_pair((llvm::MemoryBuffer*)0,
1234 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001235 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 }
1237 }
1238 }
1239
1240 // Check whether there is a file-buffer remapping. It supercedes the
1241 // file-file remapping.
1242 for (PreprocessorOptions::remapped_file_buffer_iterator
1243 M = PreprocessorOpts.remapped_file_buffer_begin(),
1244 E = PreprocessorOpts.remapped_file_buffer_end();
1245 M != E;
1246 ++M) {
1247 llvm::sys::PathWithStatus MPath(M->first);
1248 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1249 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1250 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001251 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001253 CreatedBuffer = false;
1254 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001255
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 }
1258 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001260 }
1261
1262 // If the main source file was not remapped, load it now.
1263 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001264 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001265 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001266 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001267
1268 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001269 }
1270
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001271 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001272 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001273 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001274}
1275
Douglas Gregor754f3492010-07-24 00:38:13 +00001276static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001277 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001278 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001279 llvm::MemoryBuffer *Result
1280 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1281 memcpy(const_cast<char*>(Result->getBufferStart()),
1282 Old->getBufferStart(), Old->getBufferSize());
1283 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001284 ' ', NewSize - Old->getBufferSize() - 1);
1285 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001286
Douglas Gregor754f3492010-07-24 00:38:13 +00001287 return Result;
1288}
1289
Douglas Gregor175c4a92010-07-23 23:58:40 +00001290/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1291/// the source file.
1292///
1293/// This routine will compute the preamble of the main source file. If a
1294/// non-trivial preamble is found, it will precompile that preamble into a
1295/// precompiled header so that the precompiled preamble can be used to reduce
1296/// reparsing time. If a precompiled preamble has already been constructed,
1297/// this routine will determine if it is still valid and, if so, avoid
1298/// rebuilding the precompiled preamble.
1299///
Douglas Gregordf95a132010-08-09 20:45:32 +00001300/// \param AllowRebuild When true (the default), this routine is
1301/// allowed to rebuild the precompiled preamble if it is found to be
1302/// out-of-date.
1303///
1304/// \param MaxLines When non-zero, the maximum number of lines that
1305/// can occur within the preamble.
1306///
Douglas Gregor754f3492010-07-24 00:38:13 +00001307/// \returns If the precompiled preamble can be used, returns a newly-allocated
1308/// buffer that should be used in place of the main file when doing so.
1309/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001310llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001311 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001312 bool AllowRebuild,
1313 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001314
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001315 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001316 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1317 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001318 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001319 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320
1321 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001322 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001323 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001324
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001325 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001326 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001327 if (CreatedPreambleBuffer)
1328 OwnedPreambleBuffer.reset(NewPreamble.first);
1329
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001330 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001331 // We couldn't find a preamble in the main source. Clear out the current
1332 // preamble, if we have one. It's obviously no good any more.
1333 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001334 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001335
1336 // The next time we actually see a preamble, precompile it.
1337 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001338 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001339 }
1340
1341 if (!Preamble.empty()) {
1342 // We've previously computed a preamble. Check whether we have the same
1343 // preamble now that we did before, and that there's enough space in
1344 // the main-file buffer within the precompiled preamble to fit the
1345 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001346 if (Preamble.size() == NewPreamble.second.first &&
1347 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001348 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001349 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001350 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001351 // The preamble has not changed. We may be able to re-use the precompiled
1352 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001353
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001354 // Check that none of the files used by the preamble have changed.
1355 bool AnyFileChanged = false;
1356
1357 // First, make a record of those files that have been overridden via
1358 // remapping or unsaved_files.
1359 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1360 for (PreprocessorOptions::remapped_file_iterator
1361 R = PreprocessorOpts.remapped_file_begin(),
1362 REnd = PreprocessorOpts.remapped_file_end();
1363 !AnyFileChanged && R != REnd;
1364 ++R) {
1365 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001366 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001367 // If we can't stat the file we're remapping to, assume that something
1368 // horrible happened.
1369 AnyFileChanged = true;
1370 break;
1371 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001372
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001373 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1374 StatBuf.st_mtime);
1375 }
1376 for (PreprocessorOptions::remapped_file_buffer_iterator
1377 R = PreprocessorOpts.remapped_file_buffer_begin(),
1378 REnd = PreprocessorOpts.remapped_file_buffer_end();
1379 !AnyFileChanged && R != REnd;
1380 ++R) {
1381 // FIXME: Should we actually compare the contents of file->buffer
1382 // remappings?
1383 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1384 0);
1385 }
1386
1387 // Check whether anything has changed.
1388 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1389 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1390 !AnyFileChanged && F != FEnd;
1391 ++F) {
1392 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1393 = OverriddenFiles.find(F->first());
1394 if (Overridden != OverriddenFiles.end()) {
1395 // This file was remapped; check whether the newly-mapped file
1396 // matches up with the previous mapping.
1397 if (Overridden->second != F->second)
1398 AnyFileChanged = true;
1399 continue;
1400 }
1401
1402 // The file was not remapped; check whether it has changed on disk.
1403 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001404 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001405 // If we can't stat the file, assume that something horrible happened.
1406 AnyFileChanged = true;
1407 } else if (StatBuf.st_size != F->second.first ||
1408 StatBuf.st_mtime != F->second.second)
1409 AnyFileChanged = true;
1410 }
1411
1412 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001413 // Okay! We can re-use the precompiled preamble.
1414
1415 // Set the state of the diagnostic object to mimic its state
1416 // after parsing the preamble.
1417 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001418 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001419 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001420 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001421
1422 // Create a version of the main file buffer that is padded to
1423 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001424 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001425 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001426 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001427 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001428 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001429
1430 // If we aren't allowed to rebuild the precompiled preamble, just
1431 // return now.
1432 if (!AllowRebuild)
1433 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001434
Douglas Gregor175c4a92010-07-23 23:58:40 +00001435 // We can't reuse the previously-computed preamble. Build a new one.
1436 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001437 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001438 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001439 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001440 } else if (!AllowRebuild) {
1441 // We aren't allowed to rebuild the precompiled preamble; just
1442 // return now.
1443 return 0;
1444 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001445
1446 // If the preamble rebuild counter > 1, it's because we previously
1447 // failed to build a preamble and we're not yet ready to try
1448 // again. Decrement the counter and return a failure.
1449 if (PreambleRebuildCounter > 1) {
1450 --PreambleRebuildCounter;
1451 return 0;
1452 }
1453
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001454 // Create a temporary file for the precompiled preamble. In rare
1455 // circumstances, this can fail.
1456 std::string PreamblePCHPath = GetPreamblePCHPath();
1457 if (PreamblePCHPath.empty()) {
1458 // Try again next time.
1459 PreambleRebuildCounter = 1;
1460 return 0;
1461 }
1462
Douglas Gregor175c4a92010-07-23 23:58:40 +00001463 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001464 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001465 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001466
1467 // Create a new buffer that stores the preamble. The buffer also contains
1468 // extra space for the original contents of the file (which will be present
1469 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001470 // grows.
1471 PreambleReservedSize = NewPreamble.first->getBufferSize();
1472 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001473 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001474 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001475 PreambleReservedSize *= 2;
1476
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001477 // Save the preamble text for later; we'll need to compare against it for
1478 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001479 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001480 Preamble.assign(FileMgr->getFile(MainFilename),
1481 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001482 NewPreamble.first->getBufferStart()
1483 + NewPreamble.second.first);
1484 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1485
Douglas Gregor671947b2010-08-19 01:33:06 +00001486 delete PreambleBuffer;
1487 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001488 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001489 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001490 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001491 NewPreamble.first->getBufferStart(), Preamble.size());
1492 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001493 ' ', PreambleReservedSize - Preamble.size() - 1);
1494 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495
1496 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001497 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001498 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1499
1500 // Tell the compiler invocation to generate a temporary precompiled header.
1501 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001502 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001503 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001504 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1505 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001506
1507 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001508 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001509
1510 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001511 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1512 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001513
Douglas Gregor01b6e312011-07-01 18:22:13 +00001514 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001515 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001517 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001518 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001519
1520 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001521 Clang->getTargetOpts().Features = TargetFeatures;
1522 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1523 Clang->getTargetOpts()));
1524 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001525 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1526 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001527 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001528 PreprocessorOpts.eraseRemappedFile(
1529 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001530 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531 }
1532
1533 // Inform the target of the language options.
1534 //
1535 // FIXME: We shouldn't need to do this, the target should be immutable once
1536 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001537 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001541 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001542 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001543 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001544 "IR inputs not support here!");
1545
1546 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001547 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001548 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001549 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001550 TopLevelDecls.clear();
1551 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552
1553 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555
1556 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001557 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001558 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001559
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001560 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001561 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001562 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001563 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1564 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001565 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001566 PreprocessorOpts.eraseRemappedFile(
1567 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001568 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569 }
1570
1571 Act->Execute();
1572 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001573
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001574 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001575 // There were errors parsing the preamble, so no precompiled header was
1576 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001577 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001578 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1579 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001580 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001581 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001582 PreprocessorOpts.eraseRemappedFile(
1583 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001584 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001585 }
1586
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001587 // Transfer any diagnostics generated when parsing the preamble into the set
1588 // of preamble diagnostics.
1589 PreambleDiagnostics.clear();
1590 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001591 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001592 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001593
Douglas Gregor175c4a92010-07-23 23:58:40 +00001594 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001595 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001596 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001597
1598 // Keep track of all of the files that the source manager knows about,
1599 // so we can verify whether they have changed or not.
1600 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001601 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001602 const llvm::MemoryBuffer *MainFileBuffer
1603 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1604 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1605 FEnd = SourceMgr.fileinfo_end();
1606 F != FEnd;
1607 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001608 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001609 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1610 continue;
1611
1612 FilesInPreamble[File->getName()]
1613 = std::make_pair(F->second->getSize(), File->getModificationTime());
1614 }
1615
Douglas Gregoreababfb2010-08-04 05:53:38 +00001616 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001617 PreprocessorOpts.eraseRemappedFile(
1618 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001619
1620 // If the hash of top-level entities differs from the hash of the top-level
1621 // entities the last time we rebuilt the preamble, clear out the completion
1622 // cache.
1623 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1624 CompletionCacheTopLevelHashValue = 0;
1625 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1626 }
1627
Douglas Gregor754f3492010-07-24 00:38:13 +00001628 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001629 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001630 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001631}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001632
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001633void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1634 std::vector<Decl *> Resolved;
1635 Resolved.reserve(TopLevelDeclsInPreamble.size());
1636 ExternalASTSource &Source = *getASTContext().getExternalSource();
1637 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1638 // Resolve the declaration ID to an actual declaration, possibly
1639 // deserializing the declaration in the process.
1640 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1641 if (D)
1642 Resolved.push_back(D);
1643 }
1644 TopLevelDeclsInPreamble.clear();
1645 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1646}
1647
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001648void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1649 // Steal the created target, context, and preprocessor.
1650 TheSema.reset(CI.takeSema());
1651 Consumer.reset(CI.takeASTConsumer());
1652 Ctx = &CI.getASTContext();
1653 PP = &CI.getPreprocessor();
1654 CI.setSourceManager(0);
1655 CI.setFileManager(0);
1656 Target = &CI.getTarget();
1657 Reader = CI.getModuleManager();
1658}
1659
Chris Lattner5f9e2722011-07-23 10:55:15 +00001660StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001661 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001662}
1663
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001664ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001665 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001666 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001667 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001668 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001669 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001670 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001671 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001672 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001673 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001674 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001675
1676 return AST.take();
1677}
1678
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001679ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001680 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001681 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001682 ASTUnit *Unit,
1683 bool Persistent,
1684 StringRef ResourceFilesPath,
1685 bool OnlyLocalDecls,
1686 bool CaptureDiagnostics,
1687 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001688 bool CacheCodeCompletionResults,
1689 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001690 assert(CI && "A CompilerInvocation is required");
1691
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001692 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001693 ASTUnit *AST = Unit;
1694 if (!AST) {
1695 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001696 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001697 AST = OwnAST.get();
1698 }
1699
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001700 if (!ResourceFilesPath.empty()) {
1701 // Override the resources path.
1702 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1703 }
1704 AST->OnlyLocalDecls = OnlyLocalDecls;
1705 AST->CaptureDiagnostics = CaptureDiagnostics;
1706 if (PrecompilePreamble)
1707 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001708 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001709 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001710
1711 // Recover resources if we crash before exiting this method.
1712 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001713 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001714 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1715 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001716 DiagCleanup(Diags.getPtr());
1717
1718 // We'll manage file buffers ourselves.
1719 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1720 CI->getFrontendOpts().DisableFree = false;
1721 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1722
1723 // Save the target features.
1724 AST->TargetFeatures = CI->getTargetOpts().Features;
1725
1726 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001727 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001728
1729 // Recover resources if we crash before exiting this method.
1730 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1731 CICleanup(Clang.get());
1732
1733 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001734 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001735
1736 // Set up diagnostics, capturing any diagnostics that would
1737 // otherwise be dropped.
1738 Clang->setDiagnostics(&AST->getDiagnostics());
1739
1740 // Create the target instance.
1741 Clang->getTargetOpts().Features = AST->TargetFeatures;
1742 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1743 Clang->getTargetOpts()));
1744 if (!Clang->hasTarget())
1745 return 0;
1746
1747 // Inform the target of the language options.
1748 //
1749 // FIXME: We shouldn't need to do this, the target should be immutable once
1750 // created. This complexity should be lifted elsewhere.
1751 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1752
1753 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1754 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001755 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001756 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001757 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 "IR inputs not supported here!");
1759
1760 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761 AST->TheSema.reset();
1762 AST->Ctx = 0;
1763 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001764 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765
1766 // Create a file manager object to provide access to and cache the filesystem.
1767 Clang->setFileManager(&AST->getFileManager());
1768
1769 // Create the source manager.
1770 Clang->setSourceManager(&AST->getSourceManager());
1771
1772 ASTFrontendAction *Act = Action;
1773
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001774 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001775 if (!Act) {
1776 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1777 Act = TrackerAct.get();
1778 }
1779
1780 // Recover resources if we crash before exiting this method.
1781 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1782 ActCleanup(TrackerAct.get());
1783
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001784 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1785 AST->transferASTDataFromCompilerInstance(*Clang);
1786 if (OwnAST && ErrAST)
1787 ErrAST->swap(OwnAST);
1788
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001790 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001791
1792 if (Persistent && !TrackerAct) {
1793 Clang->getPreprocessor().addPPCallbacks(
1794 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1795 std::vector<ASTConsumer*> Consumers;
1796 if (Clang->hasASTConsumer())
1797 Consumers.push_back(Clang->takeASTConsumer());
1798 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1799 AST->getCurrentTopLevelHashValue()));
1800 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1801 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001802 Act->Execute();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001803
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001804 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001805 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001806
1807 Act->EndSourceFile();
1808
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001809 if (OwnAST)
1810 return OwnAST.take();
1811 else
1812 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813}
1814
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001815bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1816 if (!Invocation)
1817 return true;
1818
1819 // We'll manage file buffers ourselves.
1820 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1821 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001822 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001823
Douglas Gregor1aa27302011-01-27 18:02:58 +00001824 // Save the target features.
1825 TargetFeatures = Invocation->getTargetOpts().Features;
1826
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001827 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001828 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001829 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001830 OverrideMainBuffer
1831 = getMainBufferWithPrecompiledPreamble(*Invocation);
1832 }
1833
Douglas Gregor213f18b2010-10-28 15:44:59 +00001834 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001835 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001836
Ted Kremenek25a11e12011-03-22 01:15:24 +00001837 // Recover resources if we crash before exiting this method.
1838 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1839 MemBufferCleanup(OverrideMainBuffer);
1840
Douglas Gregor213f18b2010-10-28 15:44:59 +00001841 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001842}
1843
Douglas Gregorabc563f2010-07-19 21:46:24 +00001844ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001845 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001846 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001847 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001848 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001849 TranslationUnitKind TUKind,
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00001850 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001851 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001852 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001853 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001854 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001855 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001856 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001857 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001858 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001859 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001860 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001861
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001862 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001863 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1864 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001865 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1866 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001867 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001868
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001869 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001870}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001871
1872ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1873 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001874 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001875 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001876 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001877 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001878 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001879 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001880 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001881 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001882 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001883 bool CacheCodeCompletionResults,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001884 bool AllowPCHWithCompilerErrors,
1885 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001886 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001887 // No diagnostics engine was provided, so create our own diagnostics object
1888 // with the default options.
1889 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001890 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1891 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001892 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001893
Chris Lattner5f9e2722011-07-23 10:55:15 +00001894 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001895
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001896 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001897
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001898 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001899
Douglas Gregore47be3e2010-11-11 00:39:14 +00001900 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001901 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001902
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001903 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001904 llvm::makeArrayRef(ArgBegin, ArgEnd),
1905 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001906 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001907 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001908 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001909
Douglas Gregor4db64a42010-01-23 00:14:00 +00001910 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001911 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1912 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1913 if (const llvm::MemoryBuffer *
1914 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1915 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1916 } else {
1917 const char *fname = fileOrBuf.get<const char *>();
1918 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1919 }
1920 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001921 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1922 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1923 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001924
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001925 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001926 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001927
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001928 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001929 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001930 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001931 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001932 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001933 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001934 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001935 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001936 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001937 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001938 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001939 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1940 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001941 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001942 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001943 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001944
1945 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001946 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1947 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001948
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001949 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1950 // Some error occurred, if caller wants to examine diagnostics, pass it the
1951 // ASTUnit.
1952 if (ErrAST) {
1953 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1954 ErrAST->swap(AST);
1955 }
1956 return 0;
1957 }
1958
1959 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001960}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001961
1962bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001963 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001964 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001965
1966 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001967
Douglas Gregor213f18b2010-10-28 15:44:59 +00001968 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001969 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001970
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001971 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001972 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001973 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001974 for (PreprocessorOptions::remapped_file_buffer_iterator
1975 R = PPOpts.remapped_file_buffer_begin(),
1976 REnd = PPOpts.remapped_file_buffer_end();
1977 R != REnd;
1978 ++R) {
1979 delete R->second;
1980 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001981 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001982 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1983 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1984 if (const llvm::MemoryBuffer *
1985 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1986 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1987 memBuf);
1988 } else {
1989 const char *fname = fileOrBuf.get<const char *>();
1990 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1991 fname);
1992 }
1993 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001994
Douglas Gregoreababfb2010-08-04 05:53:38 +00001995 // If we have a preamble file lying around, or if we might try to
1996 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001997 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001998 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001999 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002000
Douglas Gregorabc563f2010-07-19 21:46:24 +00002001 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002002 getDiagnostics().Reset();
2003 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002004 if (OverrideMainBuffer)
2005 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002006
Douglas Gregor175c4a92010-07-23 23:58:40 +00002007 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002008 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002009
2010 // If we're caching global code-completion results, and the top-level
2011 // declarations have changed, clear out the code-completion cache.
2012 if (!Result && ShouldCacheCodeCompletionResults &&
2013 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2014 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002015
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002016 // We now need to clear out the completion info related to this translation
2017 // unit; it'll be recreated if necessary.
2018 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002019
Douglas Gregor175c4a92010-07-23 23:58:40 +00002020 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002021}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002022
Douglas Gregor87c08a52010-08-13 22:48:40 +00002023//----------------------------------------------------------------------------//
2024// Code completion
2025//----------------------------------------------------------------------------//
2026
2027namespace {
2028 /// \brief Code completion consumer that combines the cached code-completion
2029 /// results from an ASTUnit with the code-completion results provided to it,
2030 /// then passes the result on to
2031 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002032 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002033 ASTUnit &AST;
2034 CodeCompleteConsumer &Next;
2035
2036 public:
2037 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00002038 bool IncludeMacros, bool IncludeCodePatterns,
2039 bool IncludeGlobals)
2040 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002041 Next.isOutputBinary()), AST(AST), Next(Next)
2042 {
2043 // Compute the set of contexts in which we will look when we don't have
2044 // any information about the specific context.
2045 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002046 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2047 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2048 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2049 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2050 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2051 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2052 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2053 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2054 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2055 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2056 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2057 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2058 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002059
David Blaikie4e4d0842012-03-11 07:00:24 +00002060 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002061 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2062 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2063 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002064 }
2065
2066 virtual void ProcessCodeCompleteResults(Sema &S,
2067 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002068 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002069 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002070
2071 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2072 OverloadCandidate *Candidates,
2073 unsigned NumCandidates) {
2074 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2075 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002076
Douglas Gregordae68752011-02-01 22:57:45 +00002077 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 return Next.getAllocator();
2079 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002080
2081 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2082 return Next.getCodeCompletionTUInfo();
2083 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002084 };
2085}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002086
Douglas Gregor5f808c22010-08-16 21:18:39 +00002087/// \brief Helper function that computes which global names are hidden by the
2088/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002089static void CalculateHiddenNames(const CodeCompletionContext &Context,
2090 CodeCompletionResult *Results,
2091 unsigned NumResults,
2092 ASTContext &Ctx,
2093 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002094 bool OnlyTagNames = false;
2095 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002096 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002097 case CodeCompletionContext::CCC_TopLevel:
2098 case CodeCompletionContext::CCC_ObjCInterface:
2099 case CodeCompletionContext::CCC_ObjCImplementation:
2100 case CodeCompletionContext::CCC_ObjCIvarList:
2101 case CodeCompletionContext::CCC_ClassStructUnion:
2102 case CodeCompletionContext::CCC_Statement:
2103 case CodeCompletionContext::CCC_Expression:
2104 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002105 case CodeCompletionContext::CCC_DotMemberAccess:
2106 case CodeCompletionContext::CCC_ArrowMemberAccess:
2107 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002108 case CodeCompletionContext::CCC_Namespace:
2109 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002110 case CodeCompletionContext::CCC_Name:
2111 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002112 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002113 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002114 break;
2115
2116 case CodeCompletionContext::CCC_EnumTag:
2117 case CodeCompletionContext::CCC_UnionTag:
2118 case CodeCompletionContext::CCC_ClassOrStructTag:
2119 OnlyTagNames = true;
2120 break;
2121
2122 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002123 case CodeCompletionContext::CCC_MacroName:
2124 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002125 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002126 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002127 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002128 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002129 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002130 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002131 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002132 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2133 case CodeCompletionContext::CCC_ObjCClassMessage:
2134 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002135 // We're looking for nothing, or we're looking for names that cannot
2136 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002137 return;
2138 }
2139
John McCall0a2c5e22010-08-25 06:19:51 +00002140 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002141 for (unsigned I = 0; I != NumResults; ++I) {
2142 if (Results[I].Kind != Result::RK_Declaration)
2143 continue;
2144
2145 unsigned IDNS
2146 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2147
2148 bool Hiding = false;
2149 if (OnlyTagNames)
2150 Hiding = (IDNS & Decl::IDNS_Tag);
2151 else {
2152 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002153 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2154 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002155 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002156 HiddenIDNS |= Decl::IDNS_Tag;
2157 Hiding = (IDNS & HiddenIDNS);
2158 }
2159
2160 if (!Hiding)
2161 continue;
2162
2163 DeclarationName Name = Results[I].Declaration->getDeclName();
2164 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2165 HiddenNames.insert(Identifier->getName());
2166 else
2167 HiddenNames.insert(Name.getAsString());
2168 }
2169}
2170
2171
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002172void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2173 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002174 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002175 unsigned NumResults) {
2176 // Merge the results we were given with the results we cached.
2177 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002178 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002179 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002180 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002181 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002182 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002183 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002184 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002185 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002186 C = AST.cached_completion_begin(),
2187 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002188 C != CEnd; ++C) {
2189 // If the context we are in matches any of the contexts we are
2190 // interested in, we'll add this result.
2191 if ((C->ShowInContexts & InContexts) == 0)
2192 continue;
2193
2194 // If we haven't added any results previously, do so now.
2195 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002196 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2197 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002198 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2199 AddedResult = true;
2200 }
2201
Douglas Gregor5f808c22010-08-16 21:18:39 +00002202 // Determine whether this global completion result is hidden by a local
2203 // completion result. If so, skip it.
2204 if (C->Kind != CXCursor_MacroDefinition &&
2205 HiddenNames.count(C->Completion->getTypedText()))
2206 continue;
2207
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002208 // Adjust priority based on similar type classes.
2209 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002210 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002211 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002212 if (!Context.getPreferredType().isNull()) {
2213 if (C->Kind == CXCursor_MacroDefinition) {
2214 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002215 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002216 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002217 } else if (C->Type) {
2218 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002219 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002220 Context.getPreferredType().getUnqualifiedType());
2221 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2222 if (ExpectedSTC == C->TypeClass) {
2223 // We know this type is similar; check for an exact match.
2224 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002225 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002226 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002227 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002228 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2229 Priority /= CCF_ExactTypeMatch;
2230 else
2231 Priority /= CCF_SimilarTypeMatch;
2232 }
2233 }
2234 }
2235
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002236 // Adjust the completion string, if required.
2237 if (C->Kind == CXCursor_MacroDefinition &&
2238 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2239 // Create a new code-completion string that just contains the
2240 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002241 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2242 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002243 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002244 CursorKind = CXCursor_NotImplemented;
2245 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002246 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002247 }
2248
Douglas Gregor4125c372010-08-25 18:03:13 +00002249 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002250 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002251 }
2252
2253 // If we did not add any cached completion results, just forward the
2254 // results we were given to the next consumer.
2255 if (!AddedResult) {
2256 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2257 return;
2258 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002259
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002260 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2261 AllResults.size());
2262}
2263
2264
2265
Chris Lattner5f9e2722011-07-23 10:55:15 +00002266void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002267 RemappedFile *RemappedFiles,
2268 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002269 bool IncludeMacros,
2270 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002271 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002272 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002273 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002274 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2275 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002276 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002277 return;
2278
Douglas Gregor213f18b2010-10-28 15:44:59 +00002279 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002280 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002281 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002282
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002283 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002284 CCInvocation(new CompilerInvocation(*Invocation));
2285
2286 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2287 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002288
Douglas Gregor87c08a52010-08-13 22:48:40 +00002289 FrontendOpts.ShowMacrosInCodeCompletion
2290 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002291 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002292 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2293 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002294 FrontendOpts.CodeCompletionAt.FileName = File;
2295 FrontendOpts.CodeCompletionAt.Line = Line;
2296 FrontendOpts.CodeCompletionAt.Column = Column;
2297
2298 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002299 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002300
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002301 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002302
2303 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002304 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2305 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002306
Ted Kremenek4f327862011-03-21 18:40:17 +00002307 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002308 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002309
2310 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002311 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002312 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002313 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002314 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002316
2317 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002318 Clang->getTargetOpts().Features = TargetFeatures;
2319 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2320 Clang->getTargetOpts()));
2321 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002322 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002323 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002324 }
2325
2326 // Inform the target of the language options.
2327 //
2328 // FIXME: We shouldn't need to do this, the target should be immutable once
2329 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002330 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002331
Ted Kremenek03201fb2011-03-21 18:40:07 +00002332 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002333 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002334 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002335 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002336 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002337 "IR inputs not support here!");
2338
2339
2340 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002341 Clang->setFileManager(&FileMgr);
2342 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002343
2344 // Remap files.
2345 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002346 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002347 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002348 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2349 if (const llvm::MemoryBuffer *
2350 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2351 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2352 OwnedBuffers.push_back(memBuf);
2353 } else {
2354 const char *fname = fileOrBuf.get<const char *>();
2355 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2356 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002357 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002358
Douglas Gregor87c08a52010-08-13 22:48:40 +00002359 // Use the code completion consumer we were given, but adding any cached
2360 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002361 AugmentedCodeCompleteConsumer *AugmentedConsumer
2362 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2363 FrontendOpts.ShowMacrosInCodeCompletion,
2364 FrontendOpts.ShowCodePatternsInCodeCompletion,
2365 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002366 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367
Douglas Gregordf95a132010-08-09 20:45:32 +00002368 // If we have a precompiled preamble, try to use it. We only allow
2369 // the use of the precompiled preamble if we're if the completion
2370 // point is within the main file, after the end of the precompiled
2371 // preamble.
2372 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002373 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002374 using llvm::sys::FileStatus;
2375 llvm::sys::PathWithStatus CompleteFilePath(File);
2376 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2377 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2378 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002379 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2380 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002381 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002382 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002383 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002384 }
2385
2386 // If the main file has been overridden due to the use of a preamble,
2387 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002388 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002389 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002390 stored_diag_begin(),
2391 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002392 if (OverrideMainBuffer) {
2393 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2394 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2395 PreprocessorOpts.PrecompiledPreambleBytes.second
2396 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002397 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002398 PreprocessorOpts.DisablePCHValidation = true;
2399
Douglas Gregor2283d792010-08-20 00:59:43 +00002400 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002401 } else {
2402 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2403 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002404 }
2405
Douglas Gregordca8ee82011-05-06 16:33:08 +00002406 // Disable the preprocessing record
2407 PreprocessorOpts.DetailedRecord = false;
2408
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002409 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002410 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002411 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002412 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002413 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002414 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2415 getSourceManager(), PreambleDiagnostics,
2416 StoredDiagnostics);
2417 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 Act->Execute();
2419 Act->EndSourceFile();
2420 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002421
2422 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002423}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002424
Chris Lattner5f9e2722011-07-23 10:55:15 +00002425CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002426 // Write to a temporary file and later rename it to the actual file, to avoid
2427 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002428 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002429 TempPath = File;
2430 TempPath += "-%%%%%%%%";
2431 int fd;
2432 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2433 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002434 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002435
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002436 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2437 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002438 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002439
2440 serialize(Out);
2441 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002442 if (Out.has_error()) {
2443 Out.clear_error();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002444 return CXSaveError_Unknown;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002445 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002446
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002447 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002448 bool exists;
2449 llvm::sys::fs::remove(TempPath.str(), exists);
2450 return CXSaveError_Unknown;
2451 }
2452
2453 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002454}
2455
Chris Lattner5f9e2722011-07-23 10:55:15 +00002456bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002457 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002458
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002459 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002460 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002461 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002462 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002463 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002464
2465 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002466 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002467 OS.write((char *)&Buffer.front(), Buffer.size());
2468
2469 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002470}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002471
2472typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2473
2474static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2475 unsigned Raw = L.getRawEncoding();
2476 const unsigned MacroBit = 1U << 31;
2477 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2478 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2479}
2480
2481void ASTUnit::TranslateStoredDiagnostics(
2482 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002483 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002484 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485 const SmallVectorImpl<StoredDiagnostic> &Diags,
2486 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002487 // The stored diagnostic has the old source manager in it; update
2488 // the locations to refer into the new source manager. We also need to remap
2489 // all the locations to the new view. This includes the diag location, any
2490 // associated source ranges, and the source ranges of associated fix-its.
2491 // FIXME: There should be a cleaner way to do this.
2492
Chris Lattner5f9e2722011-07-23 10:55:15 +00002493 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002494 Result.reserve(Diags.size());
2495 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002496 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002497 assert(Mod && "Don't have preamble module");
2498 SLocRemap &Remap = Mod->SLocRemap;
2499 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2500 // Rebuild the StoredDiagnostic.
2501 const StoredDiagnostic &SD = Diags[I];
2502 SourceLocation L = SD.getLocation();
2503 TranslateSLoc(L, Remap);
2504 FullSourceLoc Loc(L, SrcMgr);
2505
Chris Lattner5f9e2722011-07-23 10:55:15 +00002506 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002507 Ranges.reserve(SD.range_size());
2508 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2509 E = SD.range_end();
2510 I != E; ++I) {
2511 SourceLocation BL = I->getBegin();
2512 TranslateSLoc(BL, Remap);
2513 SourceLocation EL = I->getEnd();
2514 TranslateSLoc(EL, Remap);
2515 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2516 }
2517
Chris Lattner5f9e2722011-07-23 10:55:15 +00002518 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002519 FixIts.reserve(SD.fixit_size());
2520 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2521 E = SD.fixit_end();
2522 I != E; ++I) {
2523 FixIts.push_back(FixItHint());
2524 FixItHint &FH = FixIts.back();
2525 FH.CodeToInsert = I->CodeToInsert;
2526 SourceLocation BL = I->RemoveRange.getBegin();
2527 TranslateSLoc(BL, Remap);
2528 SourceLocation EL = I->RemoveRange.getEnd();
2529 TranslateSLoc(EL, Remap);
2530 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2531 I->RemoveRange.isTokenRange());
2532 }
2533
2534 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2535 SD.getMessage(), Loc, Ranges, FixIts));
2536 }
2537 Result.swap(Out);
2538}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002539
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002540static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2541 std::pair<unsigned, Decl *> R) {
2542 return L.first < R.first;
2543}
2544
2545void ASTUnit::addFileLevelDecl(Decl *D) {
2546 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002547
2548 // We only care about local declarations.
2549 if (D->isFromASTFile())
2550 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002551
2552 SourceManager &SM = *SourceMgr;
2553 SourceLocation Loc = D->getLocation();
2554 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2555 return;
2556
2557 // We only keep track of the file-level declarations of each file.
2558 if (!D->getLexicalDeclContext()->isFileContext())
2559 return;
2560
2561 SourceLocation FileLoc = SM.getFileLoc(Loc);
2562 assert(SM.isLocalSourceLocation(FileLoc));
2563 FileID FID;
2564 unsigned Offset;
2565 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2566 if (FID.isInvalid())
2567 return;
2568
2569 LocDeclsTy *&Decls = FileDecls[FID];
2570 if (!Decls)
2571 Decls = new LocDeclsTy();
2572
2573 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2574
2575 if (Decls->empty() || Decls->back().first <= Offset) {
2576 Decls->push_back(LocDecl);
2577 return;
2578 }
2579
2580 LocDeclsTy::iterator
2581 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2582
2583 Decls->insert(I, LocDecl);
2584}
2585
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002586void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2587 SmallVectorImpl<Decl *> &Decls) {
2588 if (File.isInvalid())
2589 return;
2590
2591 if (SourceMgr->isLoadedFileID(File)) {
2592 assert(Ctx->getExternalSource() && "No external source!");
2593 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2594 Decls);
2595 }
2596
2597 FileDeclsTy::iterator I = FileDecls.find(File);
2598 if (I == FileDecls.end())
2599 return;
2600
2601 LocDeclsTy &LocDecls = *I->second;
2602 if (LocDecls.empty())
2603 return;
2604
2605 LocDeclsTy::iterator
2606 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2607 std::make_pair(Offset, (Decl*)0), compLocDecl);
2608 if (BeginIt != LocDecls.begin())
2609 --BeginIt;
2610
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002611 // If we are pointing at a top-level decl inside an objc container, we need
2612 // to backtrack until we find it otherwise we will fail to report that the
2613 // region overlaps with an objc container.
2614 while (BeginIt != LocDecls.begin() &&
2615 BeginIt->second->isTopLevelDeclInObjCContainer())
2616 --BeginIt;
2617
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002618 LocDeclsTy::iterator
2619 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2620 std::make_pair(Offset+Length, (Decl*)0),
2621 compLocDecl);
2622 if (EndIt != LocDecls.end())
2623 ++EndIt;
2624
2625 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2626 Decls.push_back(DIt->second);
2627}
2628
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002629SourceLocation ASTUnit::getLocation(const FileEntry *File,
2630 unsigned Line, unsigned Col) const {
2631 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002632 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002633 return SM.getMacroArgExpandedLocation(Loc);
2634}
2635
2636SourceLocation ASTUnit::getLocation(const FileEntry *File,
2637 unsigned Offset) const {
2638 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002639 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002640 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2641}
2642
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002643/// \brief If \arg Loc is a loaded location from the preamble, returns
2644/// the corresponding local location of the main file, otherwise it returns
2645/// \arg Loc.
2646SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2647 FileID PreambleID;
2648 if (SourceMgr)
2649 PreambleID = SourceMgr->getPreambleFileID();
2650
2651 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2652 return Loc;
2653
2654 unsigned Offs;
2655 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2656 SourceLocation FileLoc
2657 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2658 return FileLoc.getLocWithOffset(Offs);
2659 }
2660
2661 return Loc;
2662}
2663
2664/// \brief If \arg Loc is a local location of the main file but inside the
2665/// preamble chunk, returns the corresponding loaded location from the
2666/// preamble, otherwise it returns \arg Loc.
2667SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2668 FileID PreambleID;
2669 if (SourceMgr)
2670 PreambleID = SourceMgr->getPreambleFileID();
2671
2672 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2673 return Loc;
2674
2675 unsigned Offs;
2676 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2677 Offs < Preamble.size()) {
2678 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2679 return FileLoc.getLocWithOffset(Offs);
2680 }
2681
2682 return Loc;
2683}
2684
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002685bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2686 FileID FID;
2687 if (SourceMgr)
2688 FID = SourceMgr->getPreambleFileID();
2689
2690 if (Loc.isInvalid() || FID.isInvalid())
2691 return false;
2692
2693 return SourceMgr->isInFileID(Loc, FID);
2694}
2695
2696bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2697 FileID FID;
2698 if (SourceMgr)
2699 FID = SourceMgr->getMainFileID();
2700
2701 if (Loc.isInvalid() || FID.isInvalid())
2702 return false;
2703
2704 return SourceMgr->isInFileID(Loc, FID);
2705}
2706
2707SourceLocation ASTUnit::getEndOfPreambleFileID() {
2708 FileID FID;
2709 if (SourceMgr)
2710 FID = SourceMgr->getPreambleFileID();
2711
2712 if (FID.isInvalid())
2713 return SourceLocation();
2714
2715 return SourceMgr->getLocForEndOfFile(FID);
2716}
2717
2718SourceLocation ASTUnit::getStartOfMainFileID() {
2719 FileID FID;
2720 if (SourceMgr)
2721 FID = SourceMgr->getMainFileID();
2722
2723 if (FID.isInvalid())
2724 return SourceLocation();
2725
2726 return SourceMgr->getLocForStartOfFile(FID);
2727}
2728
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002729void ASTUnit::PreambleData::countLines() const {
2730 NumLines = 0;
2731 if (empty())
2732 return;
2733
2734 for (std::vector<char>::const_iterator
2735 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2736 if (*I == '\n')
2737 ++NumLines;
2738 }
2739 if (Buffer.back() != '\n')
2740 ++NumLines;
2741}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002742
2743#ifndef NDEBUG
2744ASTUnit::ConcurrencyState::ConcurrencyState() {
2745 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2746}
2747
2748ASTUnit::ConcurrencyState::~ConcurrencyState() {
2749 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2750}
2751
2752void ASTUnit::ConcurrencyState::start() {
2753 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2754 assert(acquired && "Concurrent access to ASTUnit!");
2755}
2756
2757void ASTUnit::ConcurrencyState::finish() {
2758 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2759}
2760
2761#else // NDEBUG
2762
2763ASTUnit::ConcurrencyState::ConcurrencyState() {}
2764ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2765void ASTUnit::ConcurrencyState::start() {}
2766void ASTUnit::ConcurrencyState::finish() {}
2767
2768#endif