blob: 7be25e96b4c3fbd73a393938d30ef90ed618b968 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor213f18b2010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000059 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 }
64
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek1872b312011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek1872b312011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000119 // Use the mutex because there can be an alive thread destroying an ASTUnit.
120 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000121 OnDiskDataMap &M = getOnDiskDataMap();
122 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
123 // We don't worry about freeing the memory associated with OnDiskDataMap.
124 // All we care about is erasing stale files.
125 I->second->Cleanup();
126 }
127}
128
129static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000130 // We require the mutex since we are modifying the structure of the
131 // DenseMap.
132 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000133 OnDiskDataMap &M = getOnDiskDataMap();
134 OnDiskData *&D = M[AU];
135 if (!D)
136 D = new OnDiskData();
137 return *D;
138}
139
140static void erasePreambleFile(const ASTUnit *AU) {
141 getOnDiskData(AU).CleanPreambleFile();
142}
143
144static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000145 // We require the mutex since we are modifying the structure of the
146 // DenseMap.
147 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000148 OnDiskDataMap &M = getOnDiskDataMap();
149 OnDiskDataMap::iterator I = M.find(AU);
150 if (I != M.end()) {
151 I->second->Cleanup();
152 delete I->second;
153 M.erase(AU);
154 }
155}
156
157static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
166 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
167 TemporaryFiles[I].eraseFromDisk();
168 TemporaryFiles.clear();
169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::Path(PreambleFile).eraseFromDisk();
174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000183void ASTUnit::clearFileLevelDecls() {
184 for (FileDeclsTy::iterator
185 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
186 delete I->second;
187 FileDecls.clear();
188}
189
Ted Kremenek1872b312011-10-27 17:55:18 +0000190void ASTUnit::CleanTemporaryFiles() {
191 getOnDiskData(this).CleanTemporaryFiles();
192}
193
194void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
195 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000196}
197
Douglas Gregoreababfb2010-08-04 05:53:38 +0000198/// \brief After failing to build a precompiled preamble (due to
199/// errors in the source that occurs in the preamble), the number of
200/// reparses during which we'll skip even trying to precompile the
201/// preamble.
202const unsigned DefaultPreambleRebuildInterval = 5;
203
Douglas Gregore3c60a72010-11-17 00:13:31 +0000204/// \brief Tracks the number of ASTUnit objects that are currently active.
205///
206/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000207static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000208
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000209ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000210 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000211 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000212 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000213 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000214 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000215 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000216 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000217 ShouldCacheCodeCompletionResults(false),
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000218 IncludeBriefCommentsInCodeCompletion(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000219 CompletionCacheTopLevelHashValue(0),
220 PreambleTopLevelHashValue(0),
221 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000222 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000223 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000224 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000225 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
226 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000227}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000228
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000229ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000230 clearFileLevelDecls();
231
Ted Kremenek1872b312011-10-27 17:55:18 +0000232 // Clean up the temporary files and the preamble file.
233 removeOnDiskEntry(this);
234
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000235 // Free the buffers associated with remapped files. We are required to
236 // perform this operation here because we explicitly request that the
237 // compiler instance *not* free these buffers for each invocation of the
238 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000239 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000240 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
241 for (PreprocessorOptions::remapped_file_buffer_iterator
242 FB = PPOpts.remapped_file_buffer_begin(),
243 FBEnd = PPOpts.remapped_file_buffer_end();
244 FB != FBEnd;
245 ++FB)
246 delete FB->second;
247 }
Douglas Gregor28233422010-07-27 14:52:07 +0000248
249 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000250 delete PreambleBuffer;
251
Douglas Gregor213f18b2010-10-28 15:44:59 +0000252 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000253
254 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000255 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000256 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
257 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000258}
259
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000260void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
261
Douglas Gregor8071e422010-08-15 06:18:01 +0000262/// \brief Determine the set of code-completion contexts in which this
263/// declaration should be shown.
264static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
268
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 if (!ND)
272 return 0;
273
274 unsigned Contexts = 0;
275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
279 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
280 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
281 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
282 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000283 | (1 << (CodeCompletionContext::CCC_Type - 1))
284 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
288 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
289
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
293 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000294
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000297 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
301 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
302
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000304 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000306 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
307 if (Record->isUnion())
308 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
309 else
310 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
311
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000314 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
318 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
319 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000320 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
322 } else if (isa<ObjCProtocolDecl>(ND)) {
323 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
325 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000327 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000328
329 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 }
332
333 return Contexts;
334}
335
Douglas Gregor87c08a52010-08-13 22:48:40 +0000336void ASTUnit::CacheCodeCompletionResults() {
337 if (!TheSema)
338 return;
339
Douglas Gregor213f18b2010-10-28 15:44:59 +0000340 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000341 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000342
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
345
346 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000347 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000348 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000350 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
351 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352
353 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000354 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
355
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
357 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000358 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000359 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000360 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000361 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000362 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000363 getCodeCompletionTUInfo(),
364 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000365 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000366 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedResult.Priority = Results[I].Priority;
369 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000370 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000371
Douglas Gregorf5586f62010-08-16 18:08:11 +0000372 // Keep track of the type of this completion in an ASTContext-agnostic
373 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000374 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000375 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 CachedResult.Type = 0;
378 } else {
379 CanQualType CanUsageType
380 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
381 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382
383 // Determine whether we have already seen this type. If so, we save
384 // ourselves the work of formatting the type string by using the
385 // temporary, CanQualType-based hash table to find the associated value.
386 unsigned &TypeValue = CompletionTypes[CanUsageType];
387 if (TypeValue == 0) {
388 TypeValue = CompletionTypes.size();
389 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 = TypeValue;
391 }
392
393 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000394 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000395
Douglas Gregor8071e422010-08-15 06:18:01 +0000396 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000397
398 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000399 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000400 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
401 // The contexts in which a nested-name-specifier can appear in C++.
402 unsigned NNSContexts
403 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
404 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
405 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
406 | (1 << (CodeCompletionContext::CCC_Statement - 1))
407 | (1 << (CodeCompletionContext::CCC_Expression - 1))
408 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
409 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
410 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
411 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000412 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000413 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
414 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415
416 if (isa<NamespaceDecl>(Results[I].Declaration) ||
417 isa<NamespaceAliasDecl>(Results[I].Declaration))
418 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
419
420 if (unsigned RemainingContexts
421 = NNSContexts & ~CachedResult.ShowInContexts) {
422 // If there any contexts where this completion can be a
423 // nested-name-specifier but isn't already an option, create a
424 // nested-name-specifier completion.
425 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000426 CachedResult.Completion
427 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000428 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000429 getCodeCompletionTUInfo(),
430 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000431 CachedResult.ShowInContexts = RemainingContexts;
432 CachedResult.Priority = CCP_NestedNameSpecifier;
433 CachedResult.TypeClass = STC_Void;
434 CachedResult.Type = 0;
435 CachedCompletionResults.push_back(CachedResult);
436 }
437 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000438 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000439 }
440
Douglas Gregor87c08a52010-08-13 22:48:40 +0000441 case Result::RK_Keyword:
442 case Result::RK_Pattern:
443 // Ignore keywords and patterns; we don't care, since they are so
444 // easily regenerated.
445 break;
446
447 case Result::RK_Macro: {
448 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000449 CachedResult.Completion
450 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000451 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000452 getCodeCompletionTUInfo(),
453 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000454 CachedResult.ShowInContexts
455 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
456 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
457 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
458 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
459 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
460 | (1 << (CodeCompletionContext::CCC_Statement - 1))
461 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000462 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000463 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000464 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000465 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
466 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000467
Douglas Gregor87c08a52010-08-13 22:48:40 +0000468 CachedResult.Priority = Results[I].Priority;
469 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000470 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000471 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000472 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000473 CachedCompletionResults.push_back(CachedResult);
474 break;
475 }
476 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000477 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000478
479 // Save the current top-level hash value.
480 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481}
482
483void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000484 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000485 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000486 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000487}
488
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489namespace {
490
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000491/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000492/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000493class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000494 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000495 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 LangOptions &LangOpt;
497 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000498 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499 std::string &Predefines;
500 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000504 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000506 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
507 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000512 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000516 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000517 return false;
518
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000520
521 // Initialize the preprocessor.
522 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000523
524 // Initialize the ASTContext
525 Context.InitBuiltinTypes(*Target);
526
527 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000528 return false;
529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner5f9e2722011-07-23 10:55:15 +0000531 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000532 // If we've already initialized the target, don't do it again.
533 if (Target)
534 return false;
535
536 // FIXME: This is broken, we should store the TargetOptions in the AST file.
537 TargetOptions TargetOpts;
538 TargetOpts.ABI = "";
539 TargetOpts.CXXABI = "";
540 TargetOpts.CPU = "";
541 TargetOpts.Features.clear();
542 TargetOpts.Triple = Triple;
543 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000544 return false;
545 }
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000547 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000548 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000549 std::string &SuggestedPredefines,
550 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000551 Predefines = Buffers[0].Data;
552 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
553 Predefines += Buffers[I].Data;
554 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000555 return false;
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000558 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000559 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
560 }
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000562 virtual void ReadCounter(unsigned Value) {
563 Counter = Value;
564 }
565};
566
David Blaikie26e7a902011-09-26 00:01:39 +0000567class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000569
570public:
David Blaikie26e7a902011-09-26 00:01:39 +0000571 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000572 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000573 : StoredDiags(StoredDiags) { }
574
David Blaikied6471f72011-09-25 23:23:43 +0000575 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000576 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000577
578 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
579 // Just drop any diagnostics that come from cloned consumers; they'll
580 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000581 // FIXME: We'd like to be able to capture these somehow, even if it's just
582 // file/line/column, because they could occur when parsing module maps or
583 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000584 return new IgnoringDiagConsumer();
585 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000586};
587
588/// \brief RAII object that optionally captures diagnostics, if
589/// there is no diagnostic client to capture them already.
590class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000591 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000592 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000593 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000594
595public:
David Blaikied6471f72011-09-25 23:23:43 +0000596 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000598 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000599 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000600 if (RequestCapture || Diags.getClient() == 0) {
601 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000603 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000604 }
605
606 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000607 if (Diags.getClient() == &Client) {
608 Diags.takeClient();
609 Diags.setClient(PreviousClient);
610 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000611 }
612};
613
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000614} // anonymous namespace
615
David Blaikie26e7a902011-09-26 00:01:39 +0000616void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000617 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000618 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000619 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000620
Douglas Gregora88084b2010-02-18 18:08:43 +0000621 StoredDiags.push_back(StoredDiagnostic(Level, Info));
622}
623
Steve Naroff77accc12009-09-03 18:19:54 +0000624const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000625 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000626}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000627
Chris Lattner5f9e2722011-07-23 10:55:15 +0000628llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000629 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000630 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000631 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000632}
633
Douglas Gregore47be3e2010-11-11 00:39:14 +0000634/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000635void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000636 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000637 ASTUnit &AST, bool CaptureDiagnostics) {
638 if (!Diags.getPtr()) {
639 // No diagnostics engine was provided, so create our own diagnostics object
640 // with the default options.
641 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000642 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000643 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000644 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000645 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
646 ArgBegin, Client,
647 /*ShouldOwnClient=*/true,
648 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000649 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000650 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000651 }
652}
653
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000654ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000655 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000656 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000657 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000658 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000659 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000660 bool CaptureDiagnostics,
661 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000662 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000663
664 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000665 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
666 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000667 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
668 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000669 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000670
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000671 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000672
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000673 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000675 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000676 AST->FileMgr = new FileManager(FileSystemOpts);
677 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
678 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000679 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000680 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000681 AST->ASTFileLangOpts,
682 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000683
Douglas Gregor4db64a42010-01-23 00:14:00 +0000684 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000685 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
686 if (const llvm::MemoryBuffer *
687 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
688 // Create the file entry for the file that we're mapping from.
689 const FileEntry *FromFile
690 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
691 memBuf->getBufferSize(),
692 0);
693 if (!FromFile) {
694 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
695 << RemappedFiles[I].first;
696 delete memBuf;
697 continue;
698 }
699
700 // Override the contents of the "from" file with the contents of
701 // the "to" file.
702 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
703
704 } else {
705 const char *fname = fileOrBuf.get<const char *>();
706 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
707 if (!ToFile) {
708 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
709 << RemappedFiles[I].first << fname;
710 continue;
711 }
712
713 // Create the file entry for the file that we're mapping from.
714 const FileEntry *FromFile
715 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
716 ToFile->getSize(),
717 0);
718 if (!FromFile) {
719 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
720 << RemappedFiles[I].first;
721 delete memBuf;
722 continue;
723 }
724
725 // Override the contents of the "from" file with the contents of
726 // the "to" file.
727 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000728 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000729 }
730
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000731 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000733 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000734 std::string Predefines;
735 unsigned Counter;
736
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000737 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000738
Douglas Gregor998b3d32011-09-01 23:39:15 +0000739 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
740 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
741 *AST,
742 /*IILookup=*/0,
743 /*OwnsHeaderSearch=*/false,
744 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000745 Preprocessor &PP = *AST->PP;
746
747 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
748 AST->getSourceManager(),
749 /*Target=*/0,
750 PP.getIdentifierTable(),
751 PP.getSelectorTable(),
752 PP.getBuiltinInfo(),
753 /* size_reserve = */0,
754 /*DelayInitialization=*/true);
755 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000756
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000757 Reader.reset(new ASTReader(PP, Context,
758 /*isysroot=*/"",
759 /*DisableValidation=*/false,
760 /*DisableStatCache=*/false,
761 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000762
763 // Recover resources if we crash before exiting this method.
764 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
765 ReaderCleanup(Reader.get());
766
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000767 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000768 AST->ASTFileLangOpts, HeaderInfo,
769 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000770
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000771 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000772 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000773 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000775 case ASTReader::Failure:
776 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000777 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000781 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
782
Daniel Dunbard5b61262009-09-21 03:03:47 +0000783 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000784 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000786 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000787 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000788 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000789 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000790 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000791
792 // Unregister the cleanup for ASTReader. It will get cleaned up
793 // by the ASTUnit cleanup.
794 ReaderCleanup.unregister();
795
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000796 Context.setExternalSource(Source);
797
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000798 // Create an AST consumer, even though it isn't used.
799 AST->Consumer.reset(new ASTConsumer);
800
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000801 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000802 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
803 AST->TheSema->Initialize();
804 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000805 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000806
Mike Stump1eb44332009-09-09 15:08:12 +0000807 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000808}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000809
810namespace {
811
Douglas Gregor9b7db622011-02-16 18:16:54 +0000812/// \brief Preprocessor callback class that updates a hash value with the names
813/// of all macros that have been defined by the translation unit.
814class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
815 unsigned &Hash;
816
817public:
818 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
819
820 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
821 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
822 }
823};
824
825/// \brief Add the given declaration to the hash of all top-level entities.
826void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
827 if (!D)
828 return;
829
830 DeclContext *DC = D->getDeclContext();
831 if (!DC)
832 return;
833
834 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
835 return;
836
837 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
838 if (ND->getIdentifier())
839 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
840 else if (DeclarationName Name = ND->getDeclName()) {
841 std::string NameStr = Name.getAsString();
842 Hash = llvm::HashString(NameStr, Hash);
843 }
844 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000845 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000846}
847
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000848class TopLevelDeclTrackerConsumer : public ASTConsumer {
849 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000850 unsigned &Hash;
851
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000852public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
854 : Unit(_Unit), Hash(Hash) {
855 Hash = 0;
856 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000857
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000858 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000859 if (!D)
860 return;
861
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000862 // FIXME: Currently ObjC method declarations are incorrectly being
863 // reported as top-level declarations, even though their DeclContext
864 // is the containing ObjC @interface/@implementation. This is a
865 // fundamental problem in the parser right now.
866 if (isa<ObjCMethodDecl>(D))
867 return;
868
869 AddTopLevelDeclarationToHash(D, Hash);
870 Unit.addTopLevelDecl(D);
871
872 handleFileLevelDecl(D);
873 }
874
875 void handleFileLevelDecl(Decl *D) {
876 Unit.addFileLevelDecl(D);
877 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
878 for (NamespaceDecl::decl_iterator
879 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
880 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000881 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000882 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000883
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000884 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000885 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
886 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000887 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000888 }
889
Sebastian Redl27372b42010-08-11 18:52:41 +0000890 // We're not interested in "interesting" decls.
891 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000892
893 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
894 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
895 handleTopLevelDecl(*it);
896 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000897};
898
899class TopLevelDeclTrackerAction : public ASTFrontendAction {
900public:
901 ASTUnit &Unit;
902
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000903 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000904 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000905 CI.getPreprocessor().addPPCallbacks(
906 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
907 return new TopLevelDeclTrackerConsumer(Unit,
908 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000909 }
910
911public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000912 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
913
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000914 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000915 virtual TranslationUnitKind getTranslationUnitKind() {
916 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000917 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000918};
919
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000920class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000921 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000922 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000923 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000924
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000925public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000926 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000927 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000928 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000929 Hash(Unit.getCurrentTopLevelHashValue()) {
930 Hash = 0;
931 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000932
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000933 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000934 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
935 Decl *D = *it;
936 // FIXME: Currently ObjC method declarations are incorrectly being
937 // reported as top-level declarations, even though their DeclContext
938 // is the containing ObjC @interface/@implementation. This is a
939 // fundamental problem in the parser right now.
940 if (isa<ObjCMethodDecl>(D))
941 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000942 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000943 TopLevelDecls.push_back(D);
944 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000945 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000946 }
947
948 virtual void HandleTranslationUnit(ASTContext &Ctx) {
949 PCHGenerator::HandleTranslationUnit(Ctx);
950 if (!Unit.getDiagnostics().hasErrorOccurred()) {
951 // Translate the top-level declarations we captured during
952 // parsing into declaration IDs in the precompiled
953 // preamble. This will allow us to deserialize those top-level
954 // declarations when requested.
955 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
956 Unit.addTopLevelDeclFromPreamble(
957 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000958 }
959 }
960};
961
962class PrecompilePreambleAction : public ASTFrontendAction {
963 ASTUnit &Unit;
964
965public:
966 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
967
968 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000969 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000970 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000971 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000972 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000973 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
974 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000975 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000976 return 0;
977
Douglas Gregor832d6202011-07-22 16:35:34 +0000978 if (!CI.getFrontendOpts().RelocatablePCH)
979 Sysroot.clear();
980
Douglas Gregor9b7db622011-02-16 18:16:54 +0000981 CI.getPreprocessor().addPPCallbacks(
982 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000983 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
984 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000985 }
986
987 virtual bool hasCodeCompletionSupport() const { return false; }
988 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000989 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000990};
991
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000992}
993
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000994static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
995 StoredDiagnostics) {
996 // Get rid of stored diagnostics except the ones from the driver which do not
997 // have a source location.
998 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
999 if (StoredDiagnostics[I].getLocation().isValid()) {
1000 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1001 --I;
1002 }
1003 }
1004}
1005
1006static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1007 StoredDiagnostics,
1008 SourceManager &SM) {
1009 // The stored diagnostic has the old source manager in it; update
1010 // the locations to refer into the new source manager. Since we've
1011 // been careful to make sure that the source manager's state
1012 // before and after are identical, so that we can reuse the source
1013 // location itself.
1014 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1015 if (StoredDiagnostics[I].getLocation().isValid()) {
1016 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1017 StoredDiagnostics[I].setLocation(Loc);
1018 }
1019 }
1020}
1021
Douglas Gregorabc563f2010-07-19 21:46:24 +00001022/// Parse the source file into a translation unit using the given compiler
1023/// invocation, replacing the current translation unit.
1024///
1025/// \returns True if a failure occurred that causes the ASTUnit not to
1026/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001027bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001028 delete SavedMainFileBuffer;
1029 SavedMainFileBuffer = 0;
1030
Ted Kremenek4f327862011-03-21 18:40:17 +00001031 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001032 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001033 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001034 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001035
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001036 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001037 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001038
1039 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001040 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1041 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001042
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001043 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001044 CCInvocation(new CompilerInvocation(*Invocation));
1045
1046 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001047 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001048
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001049 // Set up diagnostics, capturing any diagnostics that would
1050 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001051 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001052
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001053 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001054 Clang->getTargetOpts().Features = TargetFeatures;
1055 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001056 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001057 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001058 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001059 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001060 }
1061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001062 // Inform the target of the language options.
1063 //
1064 // FIXME: We shouldn't need to do this, the target should be immutable once
1065 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001066 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001067
Ted Kremenek03201fb2011-03-21 18:40:07 +00001068 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001069 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001070 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001071 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001072 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001073 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001074
Douglas Gregorabc563f2010-07-19 21:46:24 +00001075 // Configure the various subsystems.
1076 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001077 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001078 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001079 FileMgr = new FileManager(FileSystemOpts);
1080 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001081 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001082 Ctx = 0;
1083 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001084 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001085
1086 // Clear out old caches and data.
1087 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001088 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001089 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001090
Douglas Gregorf128fed2010-08-20 00:02:33 +00001091 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001092 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001093 TopLevelDeclsInPreamble.clear();
1094 }
1095
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001096 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001097 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001098
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001099 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001100 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001101
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001102 // If the main file has been overridden due to the use of a preamble,
1103 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001104 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001105 if (OverrideMainBuffer) {
1106 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1107 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1108 PreprocessorOpts.PrecompiledPreambleBytes.second
1109 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001110 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001111 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001112
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001113 // The stored diagnostic has the old source manager in it; update
1114 // the locations to refer into the new source manager. Since we've
1115 // been careful to make sure that the source manager's state
1116 // before and after are identical, so that we can reuse the source
1117 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001118 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001119
1120 // Keep track of the override buffer;
1121 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001122 }
1123
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001124 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001125 new TopLevelDeclTrackerAction(*this));
1126
1127 // Recover resources if we crash before exiting this method.
1128 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1129 ActCleanup(Act.get());
1130
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001131 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001132 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001133
1134 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001135 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001136 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1137 getSourceManager(), PreambleDiagnostics,
1138 StoredDiagnostics);
1139 }
1140
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001141 if (!Act->Execute())
1142 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001143
1144 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001146 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001147
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001148 FailedParseDiagnostics.clear();
1149
Douglas Gregorabc563f2010-07-19 21:46:24 +00001150 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001151
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001152error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001153 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001154 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001155 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001156 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001157 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001158
1159 // Keep the ownership of the data in the ASTUnit because the client may
1160 // want to see the diagnostics.
1161 transferASTDataFromCompilerInstance(*Clang);
1162 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001163 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001164 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001165 return true;
1166}
1167
Douglas Gregor44c181a2010-07-23 00:33:23 +00001168/// \brief Simple function to retrieve a path for a preamble precompiled header.
1169static std::string GetPreamblePCHPath() {
1170 // FIXME: This is lame; sys::Path should provide this function (in particular,
1171 // it should know how to find the temporary files dir).
1172 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001173 // FIXME: This is a hack so that we can override the preamble file during
1174 // crash-recovery testing, which is the only case where the preamble files
1175 // are not necessarily cleaned up.
1176 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1177 if (TmpFile)
1178 return TmpFile;
1179
Douglas Gregor44c181a2010-07-23 00:33:23 +00001180 std::string Error;
1181 const char *TmpDir = ::getenv("TMPDIR");
1182 if (!TmpDir)
1183 TmpDir = ::getenv("TEMP");
1184 if (!TmpDir)
1185 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001186#ifdef LLVM_ON_WIN32
1187 if (!TmpDir)
1188 TmpDir = ::getenv("USERPROFILE");
1189#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001190 if (!TmpDir)
1191 TmpDir = "/tmp";
1192 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001193 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001194 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001195 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001196 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001197 return std::string();
1198
Douglas Gregor44c181a2010-07-23 00:33:23 +00001199 return P.str();
1200}
1201
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001202/// \brief Compute the preamble for the main file, providing the source buffer
1203/// that corresponds to the main file along with a pair (bytes, start-of-line)
1204/// that describes the preamble.
1205std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001206ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1207 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001208 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001209 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 CreatedBuffer = false;
1211
Douglas Gregor44c181a2010-07-23 00:33:23 +00001212 // Try to determine if the main file has been remapped, either from the
1213 // command line (to another file) or directly through the compiler invocation
1214 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001215 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001216 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1218 // Check whether there is a file-file remapping of the main file
1219 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001220 M = PreprocessorOpts.remapped_file_begin(),
1221 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001222 M != E;
1223 ++M) {
1224 llvm::sys::PathWithStatus MPath(M->first);
1225 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1226 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1227 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001228 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001230 CreatedBuffer = false;
1231 }
1232
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001233 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001235 return std::make_pair((llvm::MemoryBuffer*)0,
1236 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001237 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238 }
1239 }
1240 }
1241
1242 // Check whether there is a file-buffer remapping. It supercedes the
1243 // file-file remapping.
1244 for (PreprocessorOptions::remapped_file_buffer_iterator
1245 M = PreprocessorOpts.remapped_file_buffer_begin(),
1246 E = PreprocessorOpts.remapped_file_buffer_end();
1247 M != E;
1248 ++M) {
1249 llvm::sys::PathWithStatus MPath(M->first);
1250 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1251 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1252 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001253 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001254 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001255 CreatedBuffer = false;
1256 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257
Douglas Gregor175c4a92010-07-23 23:58:40 +00001258 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001259 }
1260 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001261 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001262 }
1263
1264 // If the main source file was not remapped, load it now.
1265 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001266 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001267 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001268 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001269
1270 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001271 }
1272
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001273 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001274 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001275 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276}
1277
Douglas Gregor754f3492010-07-24 00:38:13 +00001278static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001279 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001280 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001281 llvm::MemoryBuffer *Result
1282 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1283 memcpy(const_cast<char*>(Result->getBufferStart()),
1284 Old->getBufferStart(), Old->getBufferSize());
1285 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001286 ' ', NewSize - Old->getBufferSize() - 1);
1287 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001288
Douglas Gregor754f3492010-07-24 00:38:13 +00001289 return Result;
1290}
1291
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1293/// the source file.
1294///
1295/// This routine will compute the preamble of the main source file. If a
1296/// non-trivial preamble is found, it will precompile that preamble into a
1297/// precompiled header so that the precompiled preamble can be used to reduce
1298/// reparsing time. If a precompiled preamble has already been constructed,
1299/// this routine will determine if it is still valid and, if so, avoid
1300/// rebuilding the precompiled preamble.
1301///
Douglas Gregordf95a132010-08-09 20:45:32 +00001302/// \param AllowRebuild When true (the default), this routine is
1303/// allowed to rebuild the precompiled preamble if it is found to be
1304/// out-of-date.
1305///
1306/// \param MaxLines When non-zero, the maximum number of lines that
1307/// can occur within the preamble.
1308///
Douglas Gregor754f3492010-07-24 00:38:13 +00001309/// \returns If the precompiled preamble can be used, returns a newly-allocated
1310/// buffer that should be used in place of the main file when doing so.
1311/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001312llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001313 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001314 bool AllowRebuild,
1315 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001316
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001317 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001318 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1319 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001321 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001322
1323 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001324 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001325 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001327 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001328 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001329 if (CreatedPreambleBuffer)
1330 OwnedPreambleBuffer.reset(NewPreamble.first);
1331
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001332 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001333 // We couldn't find a preamble in the main source. Clear out the current
1334 // preamble, if we have one. It's obviously no good any more.
1335 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001336 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001337
1338 // The next time we actually see a preamble, precompile it.
1339 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001340 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001341 }
1342
1343 if (!Preamble.empty()) {
1344 // We've previously computed a preamble. Check whether we have the same
1345 // preamble now that we did before, and that there's enough space in
1346 // the main-file buffer within the precompiled preamble to fit the
1347 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001348 if (Preamble.size() == NewPreamble.second.first &&
1349 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001350 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001351 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001352 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001353 // The preamble has not changed. We may be able to re-use the precompiled
1354 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001355
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001356 // Check that none of the files used by the preamble have changed.
1357 bool AnyFileChanged = false;
1358
1359 // First, make a record of those files that have been overridden via
1360 // remapping or unsaved_files.
1361 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1362 for (PreprocessorOptions::remapped_file_iterator
1363 R = PreprocessorOpts.remapped_file_begin(),
1364 REnd = PreprocessorOpts.remapped_file_end();
1365 !AnyFileChanged && R != REnd;
1366 ++R) {
1367 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001368 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001369 // If we can't stat the file we're remapping to, assume that something
1370 // horrible happened.
1371 AnyFileChanged = true;
1372 break;
1373 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001374
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001375 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1376 StatBuf.st_mtime);
1377 }
1378 for (PreprocessorOptions::remapped_file_buffer_iterator
1379 R = PreprocessorOpts.remapped_file_buffer_begin(),
1380 REnd = PreprocessorOpts.remapped_file_buffer_end();
1381 !AnyFileChanged && R != REnd;
1382 ++R) {
1383 // FIXME: Should we actually compare the contents of file->buffer
1384 // remappings?
1385 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1386 0);
1387 }
1388
1389 // Check whether anything has changed.
1390 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1391 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1392 !AnyFileChanged && F != FEnd;
1393 ++F) {
1394 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1395 = OverriddenFiles.find(F->first());
1396 if (Overridden != OverriddenFiles.end()) {
1397 // This file was remapped; check whether the newly-mapped file
1398 // matches up with the previous mapping.
1399 if (Overridden->second != F->second)
1400 AnyFileChanged = true;
1401 continue;
1402 }
1403
1404 // The file was not remapped; check whether it has changed on disk.
1405 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001406 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001407 // If we can't stat the file, assume that something horrible happened.
1408 AnyFileChanged = true;
1409 } else if (StatBuf.st_size != F->second.first ||
1410 StatBuf.st_mtime != F->second.second)
1411 AnyFileChanged = true;
1412 }
1413
1414 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001415 // Okay! We can re-use the precompiled preamble.
1416
1417 // Set the state of the diagnostic object to mimic its state
1418 // after parsing the preamble.
1419 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001420 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001421 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001422 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001423
1424 // Create a version of the main file buffer that is padded to
1425 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001426 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001427 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001428 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001429 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001430 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001431
1432 // If we aren't allowed to rebuild the precompiled preamble, just
1433 // return now.
1434 if (!AllowRebuild)
1435 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001436
Douglas Gregor175c4a92010-07-23 23:58:40 +00001437 // We can't reuse the previously-computed preamble. Build a new one.
1438 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001439 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001440 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001441 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001442 } else if (!AllowRebuild) {
1443 // We aren't allowed to rebuild the precompiled preamble; just
1444 // return now.
1445 return 0;
1446 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001447
1448 // If the preamble rebuild counter > 1, it's because we previously
1449 // failed to build a preamble and we're not yet ready to try
1450 // again. Decrement the counter and return a failure.
1451 if (PreambleRebuildCounter > 1) {
1452 --PreambleRebuildCounter;
1453 return 0;
1454 }
1455
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001456 // Create a temporary file for the precompiled preamble. In rare
1457 // circumstances, this can fail.
1458 std::string PreamblePCHPath = GetPreamblePCHPath();
1459 if (PreamblePCHPath.empty()) {
1460 // Try again next time.
1461 PreambleRebuildCounter = 1;
1462 return 0;
1463 }
1464
Douglas Gregor175c4a92010-07-23 23:58:40 +00001465 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001466 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001467 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001468
1469 // Create a new buffer that stores the preamble. The buffer also contains
1470 // extra space for the original contents of the file (which will be present
1471 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001472 // grows.
1473 PreambleReservedSize = NewPreamble.first->getBufferSize();
1474 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001475 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001476 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001477 PreambleReservedSize *= 2;
1478
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001479 // Save the preamble text for later; we'll need to compare against it for
1480 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001481 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001482 Preamble.assign(FileMgr->getFile(MainFilename),
1483 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001484 NewPreamble.first->getBufferStart()
1485 + NewPreamble.second.first);
1486 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1487
Douglas Gregor671947b2010-08-19 01:33:06 +00001488 delete PreambleBuffer;
1489 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001490 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001491 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001492 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001493 NewPreamble.first->getBufferStart(), Preamble.size());
1494 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001495 ' ', PreambleReservedSize - Preamble.size() - 1);
1496 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001497
1498 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001499 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001500 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1501
1502 // Tell the compiler invocation to generate a temporary precompiled header.
1503 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001504 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001505 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001506 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1507 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001508
1509 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001510 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001511
1512 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001513 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1514 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001515
Douglas Gregor01b6e312011-07-01 18:22:13 +00001516 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001517 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001518
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001519 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001520 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001521
1522 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001523 Clang->getTargetOpts().Features = TargetFeatures;
1524 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1525 Clang->getTargetOpts()));
1526 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001527 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1528 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001529 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001530 PreprocessorOpts.eraseRemappedFile(
1531 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001532 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533 }
1534
1535 // Inform the target of the language options.
1536 //
1537 // FIXME: We shouldn't need to do this, the target should be immutable once
1538 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540
Ted Kremenek03201fb2011-03-21 18:40:07 +00001541 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001542 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001543 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001544 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001545 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001546 "IR inputs not support here!");
1547
1548 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001549 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001550 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001551 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001552 TopLevelDecls.clear();
1553 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001554
1555 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001556 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001557
1558 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001559 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001560 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001561
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001562 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001563 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001564 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001565 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1566 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001567 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001568 PreprocessorOpts.eraseRemappedFile(
1569 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001570 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001571 }
1572
1573 Act->Execute();
1574 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001575
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001576 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001577 // There were errors parsing the preamble, so no precompiled header was
1578 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001579 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001580 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1581 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001582 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001583 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001584 PreprocessorOpts.eraseRemappedFile(
1585 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001586 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001587 }
1588
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001589 // Transfer any diagnostics generated when parsing the preamble into the set
1590 // of preamble diagnostics.
1591 PreambleDiagnostics.clear();
1592 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001593 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001594 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001595
Douglas Gregor175c4a92010-07-23 23:58:40 +00001596 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001597 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001598 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001599
1600 // Keep track of all of the files that the source manager knows about,
1601 // so we can verify whether they have changed or not.
1602 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001603 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001604 const llvm::MemoryBuffer *MainFileBuffer
1605 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1606 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1607 FEnd = SourceMgr.fileinfo_end();
1608 F != FEnd;
1609 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001610 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001611 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1612 continue;
1613
1614 FilesInPreamble[File->getName()]
1615 = std::make_pair(F->second->getSize(), File->getModificationTime());
1616 }
1617
Douglas Gregoreababfb2010-08-04 05:53:38 +00001618 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001619 PreprocessorOpts.eraseRemappedFile(
1620 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001621
1622 // If the hash of top-level entities differs from the hash of the top-level
1623 // entities the last time we rebuilt the preamble, clear out the completion
1624 // cache.
1625 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1626 CompletionCacheTopLevelHashValue = 0;
1627 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1628 }
1629
Douglas Gregor754f3492010-07-24 00:38:13 +00001630 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001631 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001632 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001633}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001634
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001635void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1636 std::vector<Decl *> Resolved;
1637 Resolved.reserve(TopLevelDeclsInPreamble.size());
1638 ExternalASTSource &Source = *getASTContext().getExternalSource();
1639 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1640 // Resolve the declaration ID to an actual declaration, possibly
1641 // deserializing the declaration in the process.
1642 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1643 if (D)
1644 Resolved.push_back(D);
1645 }
1646 TopLevelDeclsInPreamble.clear();
1647 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1648}
1649
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001650void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1651 // Steal the created target, context, and preprocessor.
1652 TheSema.reset(CI.takeSema());
1653 Consumer.reset(CI.takeASTConsumer());
1654 Ctx = &CI.getASTContext();
1655 PP = &CI.getPreprocessor();
1656 CI.setSourceManager(0);
1657 CI.setFileManager(0);
1658 Target = &CI.getTarget();
1659 Reader = CI.getModuleManager();
1660}
1661
Chris Lattner5f9e2722011-07-23 10:55:15 +00001662StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001663 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001664}
1665
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001666ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001667 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001668 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001669 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001670 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001671 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001672 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001673 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001674 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001675 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001677
1678 return AST.take();
1679}
1680
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001681ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001682 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001683 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001684 ASTUnit *Unit,
1685 bool Persistent,
1686 StringRef ResourceFilesPath,
1687 bool OnlyLocalDecls,
1688 bool CaptureDiagnostics,
1689 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001690 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001691 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001692 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001693 assert(CI && "A CompilerInvocation is required");
1694
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001695 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001696 ASTUnit *AST = Unit;
1697 if (!AST) {
1698 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001699 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001700 AST = OwnAST.get();
1701 }
1702
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001703 if (!ResourceFilesPath.empty()) {
1704 // Override the resources path.
1705 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1706 }
1707 AST->OnlyLocalDecls = OnlyLocalDecls;
1708 AST->CaptureDiagnostics = CaptureDiagnostics;
1709 if (PrecompilePreamble)
1710 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001711 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001712 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001713 AST->IncludeBriefCommentsInCodeCompletion
1714 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001715
1716 // Recover resources if we crash before exiting this method.
1717 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001718 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001719 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1720 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001721 DiagCleanup(Diags.getPtr());
1722
1723 // We'll manage file buffers ourselves.
1724 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1725 CI->getFrontendOpts().DisableFree = false;
1726 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1727
1728 // Save the target features.
1729 AST->TargetFeatures = CI->getTargetOpts().Features;
1730
1731 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001732 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001733
1734 // Recover resources if we crash before exiting this method.
1735 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1736 CICleanup(Clang.get());
1737
1738 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001739 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001740
1741 // Set up diagnostics, capturing any diagnostics that would
1742 // otherwise be dropped.
1743 Clang->setDiagnostics(&AST->getDiagnostics());
1744
1745 // Create the target instance.
1746 Clang->getTargetOpts().Features = AST->TargetFeatures;
1747 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1748 Clang->getTargetOpts()));
1749 if (!Clang->hasTarget())
1750 return 0;
1751
1752 // Inform the target of the language options.
1753 //
1754 // FIXME: We shouldn't need to do this, the target should be immutable once
1755 // created. This complexity should be lifted elsewhere.
1756 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1757
1758 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1759 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001760 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001762 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001763 "IR inputs not supported here!");
1764
1765 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001766 AST->TheSema.reset();
1767 AST->Ctx = 0;
1768 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001769 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001770
1771 // Create a file manager object to provide access to and cache the filesystem.
1772 Clang->setFileManager(&AST->getFileManager());
1773
1774 // Create the source manager.
1775 Clang->setSourceManager(&AST->getSourceManager());
1776
1777 ASTFrontendAction *Act = Action;
1778
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001779 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780 if (!Act) {
1781 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1782 Act = TrackerAct.get();
1783 }
1784
1785 // Recover resources if we crash before exiting this method.
1786 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1787 ActCleanup(TrackerAct.get());
1788
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001789 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1790 AST->transferASTDataFromCompilerInstance(*Clang);
1791 if (OwnAST && ErrAST)
1792 ErrAST->swap(OwnAST);
1793
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001794 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001795 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001796
1797 if (Persistent && !TrackerAct) {
1798 Clang->getPreprocessor().addPPCallbacks(
1799 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1800 std::vector<ASTConsumer*> Consumers;
1801 if (Clang->hasASTConsumer())
1802 Consumers.push_back(Clang->takeASTConsumer());
1803 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1804 AST->getCurrentTopLevelHashValue()));
1805 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1806 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001807 if (!Act->Execute()) {
1808 AST->transferASTDataFromCompilerInstance(*Clang);
1809 if (OwnAST && ErrAST)
1810 ErrAST->swap(OwnAST);
1811
1812 return 0;
1813 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001814
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001815 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001816 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001817
1818 Act->EndSourceFile();
1819
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001820 if (OwnAST)
1821 return OwnAST.take();
1822 else
1823 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001824}
1825
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001826bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1827 if (!Invocation)
1828 return true;
1829
1830 // We'll manage file buffers ourselves.
1831 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1832 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001833 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001834
Douglas Gregor1aa27302011-01-27 18:02:58 +00001835 // Save the target features.
1836 TargetFeatures = Invocation->getTargetOpts().Features;
1837
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001838 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001839 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001840 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001841 OverrideMainBuffer
1842 = getMainBufferWithPrecompiledPreamble(*Invocation);
1843 }
1844
Douglas Gregor213f18b2010-10-28 15:44:59 +00001845 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001846 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001847
Ted Kremenek25a11e12011-03-22 01:15:24 +00001848 // Recover resources if we crash before exiting this method.
1849 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1850 MemBufferCleanup(OverrideMainBuffer);
1851
Douglas Gregor213f18b2010-10-28 15:44:59 +00001852 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001853}
1854
Douglas Gregorabc563f2010-07-19 21:46:24 +00001855ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001856 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001857 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001858 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001859 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001860 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001861 bool CacheCodeCompletionResults,
1862 bool IncludeBriefCommentsInCodeCompletion) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001863 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001864 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001865 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001866 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001867 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001868 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001869 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001870 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001871 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001872 AST->IncludeBriefCommentsInCodeCompletion
1873 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001874 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001875
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001876 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001877 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1878 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001879 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1880 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001881 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001882
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001883 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001884}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001885
1886ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1887 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001888 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001889 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001890 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001891 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001892 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001893 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001894 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001895 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001896 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001897 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001898 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001899 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001900 bool SkipFunctionBodies,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001901 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001902 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001903 // No diagnostics engine was provided, so create our own diagnostics object
1904 // with the default options.
1905 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001906 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1907 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001908 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001909
Chris Lattner5f9e2722011-07-23 10:55:15 +00001910 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001912 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001913
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001914 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001915
Douglas Gregore47be3e2010-11-11 00:39:14 +00001916 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001917 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001918
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001919 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001920 llvm::makeArrayRef(ArgBegin, ArgEnd),
1921 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001922 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001923 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001924 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001925
Douglas Gregor4db64a42010-01-23 00:14:00 +00001926 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001927 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1928 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1929 if (const llvm::MemoryBuffer *
1930 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1931 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1932 } else {
1933 const char *fname = fileOrBuf.get<const char *>();
1934 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1935 }
1936 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001937 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1938 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1939 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001940
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001941 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001942 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001943
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001944 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1945
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001946 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001947 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001948 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001949 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001950 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001951 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001952 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001953 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001954 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001955 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001956 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001957 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001958 AST->IncludeBriefCommentsInCodeCompletion
1959 = IncludeBriefCommentsInCodeCompletion;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001960 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001961 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001962 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001963 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001964
1965 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001966 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1967 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001968
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001969 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1970 // Some error occurred, if caller wants to examine diagnostics, pass it the
1971 // ASTUnit.
1972 if (ErrAST) {
1973 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1974 ErrAST->swap(AST);
1975 }
1976 return 0;
1977 }
1978
1979 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001980}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001981
1982bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001983 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001984 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001985
1986 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001987
Douglas Gregor213f18b2010-10-28 15:44:59 +00001988 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001989 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001990
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001991 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001992 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001993 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001994 for (PreprocessorOptions::remapped_file_buffer_iterator
1995 R = PPOpts.remapped_file_buffer_begin(),
1996 REnd = PPOpts.remapped_file_buffer_end();
1997 R != REnd;
1998 ++R) {
1999 delete R->second;
2000 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002001 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002002 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2003 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2004 if (const llvm::MemoryBuffer *
2005 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2006 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2007 memBuf);
2008 } else {
2009 const char *fname = fileOrBuf.get<const char *>();
2010 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2011 fname);
2012 }
2013 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002014
Douglas Gregoreababfb2010-08-04 05:53:38 +00002015 // If we have a preamble file lying around, or if we might try to
2016 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002017 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002018 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002019 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002020
Douglas Gregorabc563f2010-07-19 21:46:24 +00002021 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002022 getDiagnostics().Reset();
2023 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002024 if (OverrideMainBuffer)
2025 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002026
Douglas Gregor175c4a92010-07-23 23:58:40 +00002027 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002028 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002029
2030 // If we're caching global code-completion results, and the top-level
2031 // declarations have changed, clear out the code-completion cache.
2032 if (!Result && ShouldCacheCodeCompletionResults &&
2033 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2034 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002035
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002036 // We now need to clear out the completion info related to this translation
2037 // unit; it'll be recreated if necessary.
2038 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002039
Douglas Gregor175c4a92010-07-23 23:58:40 +00002040 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002041}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002042
Douglas Gregor87c08a52010-08-13 22:48:40 +00002043//----------------------------------------------------------------------------//
2044// Code completion
2045//----------------------------------------------------------------------------//
2046
2047namespace {
2048 /// \brief Code completion consumer that combines the cached code-completion
2049 /// results from an ASTUnit with the code-completion results provided to it,
2050 /// then passes the result on to
2051 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002052 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002053 ASTUnit &AST;
2054 CodeCompleteConsumer &Next;
2055
2056 public:
2057 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002058 const CodeCompleteOptions &CodeCompleteOpts)
2059 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2060 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002061 {
2062 // Compute the set of contexts in which we will look when we don't have
2063 // any information about the specific context.
2064 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002065 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2066 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2067 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2068 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2069 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2070 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2071 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2072 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2073 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2074 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2075 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2076 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2077 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002078
David Blaikie4e4d0842012-03-11 07:00:24 +00002079 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002080 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2081 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2082 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002083 }
2084
2085 virtual void ProcessCodeCompleteResults(Sema &S,
2086 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002087 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002088 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002089
2090 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2091 OverloadCandidate *Candidates,
2092 unsigned NumCandidates) {
2093 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2094 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002095
Douglas Gregordae68752011-02-01 22:57:45 +00002096 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002097 return Next.getAllocator();
2098 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002099
2100 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2101 return Next.getCodeCompletionTUInfo();
2102 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002103 };
2104}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002105
Douglas Gregor5f808c22010-08-16 21:18:39 +00002106/// \brief Helper function that computes which global names are hidden by the
2107/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002108static void CalculateHiddenNames(const CodeCompletionContext &Context,
2109 CodeCompletionResult *Results,
2110 unsigned NumResults,
2111 ASTContext &Ctx,
2112 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002113 bool OnlyTagNames = false;
2114 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002115 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002116 case CodeCompletionContext::CCC_TopLevel:
2117 case CodeCompletionContext::CCC_ObjCInterface:
2118 case CodeCompletionContext::CCC_ObjCImplementation:
2119 case CodeCompletionContext::CCC_ObjCIvarList:
2120 case CodeCompletionContext::CCC_ClassStructUnion:
2121 case CodeCompletionContext::CCC_Statement:
2122 case CodeCompletionContext::CCC_Expression:
2123 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002124 case CodeCompletionContext::CCC_DotMemberAccess:
2125 case CodeCompletionContext::CCC_ArrowMemberAccess:
2126 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002127 case CodeCompletionContext::CCC_Namespace:
2128 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002129 case CodeCompletionContext::CCC_Name:
2130 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002131 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002132 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002133 break;
2134
2135 case CodeCompletionContext::CCC_EnumTag:
2136 case CodeCompletionContext::CCC_UnionTag:
2137 case CodeCompletionContext::CCC_ClassOrStructTag:
2138 OnlyTagNames = true;
2139 break;
2140
2141 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002142 case CodeCompletionContext::CCC_MacroName:
2143 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002144 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002145 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002146 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002147 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002148 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002149 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002150 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002151 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2152 case CodeCompletionContext::CCC_ObjCClassMessage:
2153 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002154 // We're looking for nothing, or we're looking for names that cannot
2155 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002156 return;
2157 }
2158
John McCall0a2c5e22010-08-25 06:19:51 +00002159 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002160 for (unsigned I = 0; I != NumResults; ++I) {
2161 if (Results[I].Kind != Result::RK_Declaration)
2162 continue;
2163
2164 unsigned IDNS
2165 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2166
2167 bool Hiding = false;
2168 if (OnlyTagNames)
2169 Hiding = (IDNS & Decl::IDNS_Tag);
2170 else {
2171 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002172 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2173 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002174 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002175 HiddenIDNS |= Decl::IDNS_Tag;
2176 Hiding = (IDNS & HiddenIDNS);
2177 }
2178
2179 if (!Hiding)
2180 continue;
2181
2182 DeclarationName Name = Results[I].Declaration->getDeclName();
2183 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2184 HiddenNames.insert(Identifier->getName());
2185 else
2186 HiddenNames.insert(Name.getAsString());
2187 }
2188}
2189
2190
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002191void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2192 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002193 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002194 unsigned NumResults) {
2195 // Merge the results we were given with the results we cached.
2196 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002198 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002199 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002200 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002201 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002202 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002203 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002204 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002205 C = AST.cached_completion_begin(),
2206 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002207 C != CEnd; ++C) {
2208 // If the context we are in matches any of the contexts we are
2209 // interested in, we'll add this result.
2210 if ((C->ShowInContexts & InContexts) == 0)
2211 continue;
2212
2213 // If we haven't added any results previously, do so now.
2214 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002215 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2216 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002217 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2218 AddedResult = true;
2219 }
2220
Douglas Gregor5f808c22010-08-16 21:18:39 +00002221 // Determine whether this global completion result is hidden by a local
2222 // completion result. If so, skip it.
2223 if (C->Kind != CXCursor_MacroDefinition &&
2224 HiddenNames.count(C->Completion->getTypedText()))
2225 continue;
2226
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002227 // Adjust priority based on similar type classes.
2228 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002229 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002230 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002231 if (!Context.getPreferredType().isNull()) {
2232 if (C->Kind == CXCursor_MacroDefinition) {
2233 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002234 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002235 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002236 } else if (C->Type) {
2237 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002238 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002239 Context.getPreferredType().getUnqualifiedType());
2240 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2241 if (ExpectedSTC == C->TypeClass) {
2242 // We know this type is similar; check for an exact match.
2243 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002244 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002245 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002246 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002247 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2248 Priority /= CCF_ExactTypeMatch;
2249 else
2250 Priority /= CCF_SimilarTypeMatch;
2251 }
2252 }
2253 }
2254
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002255 // Adjust the completion string, if required.
2256 if (C->Kind == CXCursor_MacroDefinition &&
2257 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2258 // Create a new code-completion string that just contains the
2259 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002260 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2261 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002262 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002263 CursorKind = CXCursor_NotImplemented;
2264 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002265 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002266 }
2267
Douglas Gregor4125c372010-08-25 18:03:13 +00002268 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002269 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002270 }
2271
2272 // If we did not add any cached completion results, just forward the
2273 // results we were given to the next consumer.
2274 if (!AddedResult) {
2275 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2276 return;
2277 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002278
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002279 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2280 AllResults.size());
2281}
2282
2283
2284
Chris Lattner5f9e2722011-07-23 10:55:15 +00002285void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002286 RemappedFile *RemappedFiles,
2287 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002288 bool IncludeMacros,
2289 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002290 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002291 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002292 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002293 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002294 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2295 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002296 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002297 return;
2298
Douglas Gregor213f18b2010-10-28 15:44:59 +00002299 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002300 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002301 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002302
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002303 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002304 CCInvocation(new CompilerInvocation(*Invocation));
2305
2306 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002307 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002308 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002309
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002310 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2311 CachedCompletionResults.empty();
2312 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2313 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2314 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2315
2316 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2317
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002318 FrontendOpts.CodeCompletionAt.FileName = File;
2319 FrontendOpts.CodeCompletionAt.Line = Line;
2320 FrontendOpts.CodeCompletionAt.Column = Column;
2321
2322 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002323 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002324
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002325 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002326
2327 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002328 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2329 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002330
Ted Kremenek4f327862011-03-21 18:40:17 +00002331 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002332 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002333
2334 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002335 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002336 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002337 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002338 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002339 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002340
2341 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002342 Clang->getTargetOpts().Features = TargetFeatures;
2343 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2344 Clang->getTargetOpts()));
2345 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002346 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002347 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 }
2349
2350 // Inform the target of the language options.
2351 //
2352 // FIXME: We shouldn't need to do this, the target should be immutable once
2353 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002354 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355
Ted Kremenek03201fb2011-03-21 18:40:07 +00002356 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002357 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002358 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002359 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002360 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002361 "IR inputs not support here!");
2362
2363
2364 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002365 Clang->setFileManager(&FileMgr);
2366 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367
2368 // Remap files.
2369 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002370 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002371 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002372 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2373 if (const llvm::MemoryBuffer *
2374 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2375 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2376 OwnedBuffers.push_back(memBuf);
2377 } else {
2378 const char *fname = fileOrBuf.get<const char *>();
2379 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2380 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002381 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382
Douglas Gregor87c08a52010-08-13 22:48:40 +00002383 // Use the code completion consumer we were given, but adding any cached
2384 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002385 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002386 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002387 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002388
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002389 Clang->getFrontendOpts().SkipFunctionBodies = true;
2390
Douglas Gregordf95a132010-08-09 20:45:32 +00002391 // If we have a precompiled preamble, try to use it. We only allow
2392 // the use of the precompiled preamble if we're if the completion
2393 // point is within the main file, after the end of the precompiled
2394 // preamble.
2395 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002396 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002397 using llvm::sys::FileStatus;
2398 llvm::sys::PathWithStatus CompleteFilePath(File);
2399 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2400 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2401 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002402 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2403 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002404 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002405 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002406 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002407 }
2408
2409 // If the main file has been overridden due to the use of a preamble,
2410 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002411 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002412 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002413 stored_diag_begin(),
2414 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002415 if (OverrideMainBuffer) {
2416 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2417 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2418 PreprocessorOpts.PrecompiledPreambleBytes.second
2419 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002420 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002421 PreprocessorOpts.DisablePCHValidation = true;
2422
Douglas Gregor2283d792010-08-20 00:59:43 +00002423 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002424 } else {
2425 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2426 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002427 }
2428
Douglas Gregordca8ee82011-05-06 16:33:08 +00002429 // Disable the preprocessing record
2430 PreprocessorOpts.DetailedRecord = false;
2431
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002432 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002433 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002434 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002435 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002436 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002437 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2438 getSourceManager(), PreambleDiagnostics,
2439 StoredDiagnostics);
2440 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002441 Act->Execute();
2442 Act->EndSourceFile();
2443 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002444
2445 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002446}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002447
Chris Lattner5f9e2722011-07-23 10:55:15 +00002448CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002449 // Write to a temporary file and later rename it to the actual file, to avoid
2450 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002451 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002452 TempPath = File;
2453 TempPath += "-%%%%%%%%";
2454 int fd;
2455 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2456 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002457 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002458
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002459 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2460 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002461 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002462
2463 serialize(Out);
2464 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002465 if (Out.has_error()) {
2466 Out.clear_error();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002467 return CXSaveError_Unknown;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002468 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002469
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002470 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002471 bool exists;
2472 llvm::sys::fs::remove(TempPath.str(), exists);
2473 return CXSaveError_Unknown;
2474 }
2475
2476 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002477}
2478
Chris Lattner5f9e2722011-07-23 10:55:15 +00002479bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002480 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002481
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002482 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002483 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002484 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002485 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002486 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002487
2488 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002489 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002490 OS.write((char *)&Buffer.front(), Buffer.size());
2491
2492 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002493}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002494
2495typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2496
2497static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2498 unsigned Raw = L.getRawEncoding();
2499 const unsigned MacroBit = 1U << 31;
2500 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2501 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2502}
2503
2504void ASTUnit::TranslateStoredDiagnostics(
2505 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002506 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002507 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002508 const SmallVectorImpl<StoredDiagnostic> &Diags,
2509 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002510 // The stored diagnostic has the old source manager in it; update
2511 // the locations to refer into the new source manager. We also need to remap
2512 // all the locations to the new view. This includes the diag location, any
2513 // associated source ranges, and the source ranges of associated fix-its.
2514 // FIXME: There should be a cleaner way to do this.
2515
Chris Lattner5f9e2722011-07-23 10:55:15 +00002516 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002517 Result.reserve(Diags.size());
2518 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002519 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002520 assert(Mod && "Don't have preamble module");
2521 SLocRemap &Remap = Mod->SLocRemap;
2522 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2523 // Rebuild the StoredDiagnostic.
2524 const StoredDiagnostic &SD = Diags[I];
2525 SourceLocation L = SD.getLocation();
2526 TranslateSLoc(L, Remap);
2527 FullSourceLoc Loc(L, SrcMgr);
2528
Chris Lattner5f9e2722011-07-23 10:55:15 +00002529 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002530 Ranges.reserve(SD.range_size());
2531 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2532 E = SD.range_end();
2533 I != E; ++I) {
2534 SourceLocation BL = I->getBegin();
2535 TranslateSLoc(BL, Remap);
2536 SourceLocation EL = I->getEnd();
2537 TranslateSLoc(EL, Remap);
2538 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2539 }
2540
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002542 FixIts.reserve(SD.fixit_size());
2543 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2544 E = SD.fixit_end();
2545 I != E; ++I) {
2546 FixIts.push_back(FixItHint());
2547 FixItHint &FH = FixIts.back();
2548 FH.CodeToInsert = I->CodeToInsert;
2549 SourceLocation BL = I->RemoveRange.getBegin();
2550 TranslateSLoc(BL, Remap);
2551 SourceLocation EL = I->RemoveRange.getEnd();
2552 TranslateSLoc(EL, Remap);
2553 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2554 I->RemoveRange.isTokenRange());
2555 }
2556
2557 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2558 SD.getMessage(), Loc, Ranges, FixIts));
2559 }
2560 Result.swap(Out);
2561}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002562
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002563static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2564 std::pair<unsigned, Decl *> R) {
2565 return L.first < R.first;
2566}
2567
2568void ASTUnit::addFileLevelDecl(Decl *D) {
2569 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002570
2571 // We only care about local declarations.
2572 if (D->isFromASTFile())
2573 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002574
2575 SourceManager &SM = *SourceMgr;
2576 SourceLocation Loc = D->getLocation();
2577 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2578 return;
2579
2580 // We only keep track of the file-level declarations of each file.
2581 if (!D->getLexicalDeclContext()->isFileContext())
2582 return;
2583
2584 SourceLocation FileLoc = SM.getFileLoc(Loc);
2585 assert(SM.isLocalSourceLocation(FileLoc));
2586 FileID FID;
2587 unsigned Offset;
2588 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2589 if (FID.isInvalid())
2590 return;
2591
2592 LocDeclsTy *&Decls = FileDecls[FID];
2593 if (!Decls)
2594 Decls = new LocDeclsTy();
2595
2596 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2597
2598 if (Decls->empty() || Decls->back().first <= Offset) {
2599 Decls->push_back(LocDecl);
2600 return;
2601 }
2602
2603 LocDeclsTy::iterator
2604 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2605
2606 Decls->insert(I, LocDecl);
2607}
2608
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002609void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2610 SmallVectorImpl<Decl *> &Decls) {
2611 if (File.isInvalid())
2612 return;
2613
2614 if (SourceMgr->isLoadedFileID(File)) {
2615 assert(Ctx->getExternalSource() && "No external source!");
2616 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2617 Decls);
2618 }
2619
2620 FileDeclsTy::iterator I = FileDecls.find(File);
2621 if (I == FileDecls.end())
2622 return;
2623
2624 LocDeclsTy &LocDecls = *I->second;
2625 if (LocDecls.empty())
2626 return;
2627
2628 LocDeclsTy::iterator
2629 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2630 std::make_pair(Offset, (Decl*)0), compLocDecl);
2631 if (BeginIt != LocDecls.begin())
2632 --BeginIt;
2633
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002634 // If we are pointing at a top-level decl inside an objc container, we need
2635 // to backtrack until we find it otherwise we will fail to report that the
2636 // region overlaps with an objc container.
2637 while (BeginIt != LocDecls.begin() &&
2638 BeginIt->second->isTopLevelDeclInObjCContainer())
2639 --BeginIt;
2640
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002641 LocDeclsTy::iterator
2642 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2643 std::make_pair(Offset+Length, (Decl*)0),
2644 compLocDecl);
2645 if (EndIt != LocDecls.end())
2646 ++EndIt;
2647
2648 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2649 Decls.push_back(DIt->second);
2650}
2651
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002652SourceLocation ASTUnit::getLocation(const FileEntry *File,
2653 unsigned Line, unsigned Col) const {
2654 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002655 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002656 return SM.getMacroArgExpandedLocation(Loc);
2657}
2658
2659SourceLocation ASTUnit::getLocation(const FileEntry *File,
2660 unsigned Offset) const {
2661 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002662 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002663 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2664}
2665
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002666/// \brief If \arg Loc is a loaded location from the preamble, returns
2667/// the corresponding local location of the main file, otherwise it returns
2668/// \arg Loc.
2669SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2670 FileID PreambleID;
2671 if (SourceMgr)
2672 PreambleID = SourceMgr->getPreambleFileID();
2673
2674 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2675 return Loc;
2676
2677 unsigned Offs;
2678 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2679 SourceLocation FileLoc
2680 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2681 return FileLoc.getLocWithOffset(Offs);
2682 }
2683
2684 return Loc;
2685}
2686
2687/// \brief If \arg Loc is a local location of the main file but inside the
2688/// preamble chunk, returns the corresponding loaded location from the
2689/// preamble, otherwise it returns \arg Loc.
2690SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2691 FileID PreambleID;
2692 if (SourceMgr)
2693 PreambleID = SourceMgr->getPreambleFileID();
2694
2695 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2696 return Loc;
2697
2698 unsigned Offs;
2699 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2700 Offs < Preamble.size()) {
2701 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2702 return FileLoc.getLocWithOffset(Offs);
2703 }
2704
2705 return Loc;
2706}
2707
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002708bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2709 FileID FID;
2710 if (SourceMgr)
2711 FID = SourceMgr->getPreambleFileID();
2712
2713 if (Loc.isInvalid() || FID.isInvalid())
2714 return false;
2715
2716 return SourceMgr->isInFileID(Loc, FID);
2717}
2718
2719bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2720 FileID FID;
2721 if (SourceMgr)
2722 FID = SourceMgr->getMainFileID();
2723
2724 if (Loc.isInvalid() || FID.isInvalid())
2725 return false;
2726
2727 return SourceMgr->isInFileID(Loc, FID);
2728}
2729
2730SourceLocation ASTUnit::getEndOfPreambleFileID() {
2731 FileID FID;
2732 if (SourceMgr)
2733 FID = SourceMgr->getPreambleFileID();
2734
2735 if (FID.isInvalid())
2736 return SourceLocation();
2737
2738 return SourceMgr->getLocForEndOfFile(FID);
2739}
2740
2741SourceLocation ASTUnit::getStartOfMainFileID() {
2742 FileID FID;
2743 if (SourceMgr)
2744 FID = SourceMgr->getMainFileID();
2745
2746 if (FID.isInvalid())
2747 return SourceLocation();
2748
2749 return SourceMgr->getLocForStartOfFile(FID);
2750}
2751
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002752void ASTUnit::PreambleData::countLines() const {
2753 NumLines = 0;
2754 if (empty())
2755 return;
2756
2757 for (std::vector<char>::const_iterator
2758 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2759 if (*I == '\n')
2760 ++NumLines;
2761 }
2762 if (Buffer.back() != '\n')
2763 ++NumLines;
2764}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002765
2766#ifndef NDEBUG
2767ASTUnit::ConcurrencyState::ConcurrencyState() {
2768 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2769}
2770
2771ASTUnit::ConcurrencyState::~ConcurrencyState() {
2772 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2773}
2774
2775void ASTUnit::ConcurrencyState::start() {
2776 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2777 assert(acquired && "Concurrent access to ASTUnit!");
2778}
2779
2780void ASTUnit::ConcurrencyState::finish() {
2781 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2782}
2783
2784#else // NDEBUG
2785
2786ASTUnit::ConcurrencyState::ConcurrencyState() {}
2787ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2788void ASTUnit::ConcurrencyState::start() {}
2789void ASTUnit::ConcurrencyState::finish() {}
2790
2791#endif