blob: d0aadfd29ea97f6d1602ee3c77519177e43444c9 [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),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000218 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(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
Richard Smith026b3582012-08-14 03:13:00 +0000274 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 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))
Richard Smith026b3582012-08-14 03:13:00 +0000279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
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))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
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))
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
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())
Richard Smith026b3582012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 else
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
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.
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
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++.
Richard Smith026b3582012-08-14 03:13:00 +0000402 uint64_t NNSContexts
403 = (1LL << CodeCompletionContext::CCC_TopLevel)
404 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
405 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
406 | (1LL << CodeCompletionContext::CCC_Statement)
407 | (1LL << CodeCompletionContext::CCC_Expression)
408 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
409 | (1LL << CodeCompletionContext::CCC_EnumTag)
410 | (1LL << CodeCompletionContext::CCC_UnionTag)
411 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
412 | (1LL << CodeCompletionContext::CCC_Type)
413 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
414 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415
416 if (isa<NamespaceDecl>(Results[I].Declaration) ||
417 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000418 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000419
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
Richard Smith026b3582012-08-14 03:13:00 +0000455 = (1LL << CodeCompletionContext::CCC_TopLevel)
456 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
457 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
458 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
459 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
460 | (1LL << CodeCompletionContext::CCC_Statement)
461 | (1LL << CodeCompletionContext::CCC_Expression)
462 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
463 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
464 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
465 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
466 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
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 Kyrtzidis7f186332012-09-14 20:24:53 +0000528
529 applyLangOptsToTarget();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000530 return false;
531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Chris Lattner5f9e2722011-07-23 10:55:15 +0000533 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000534 // If we've already initialized the target, don't do it again.
535 if (Target)
536 return false;
537
538 // FIXME: This is broken, we should store the TargetOptions in the AST file.
539 TargetOptions TargetOpts;
540 TargetOpts.ABI = "";
541 TargetOpts.CXXABI = "";
542 TargetOpts.CPU = "";
543 TargetOpts.Features.clear();
544 TargetOpts.Triple = Triple;
545 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000546
547 applyLangOptsToTarget();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000548 return false;
549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000551 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000552 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000553 std::string &SuggestedPredefines,
554 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000555 Predefines = Buffers[0].Data;
556 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
557 Predefines += Buffers[I].Data;
558 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000559 return false;
560 }
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000562 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000563 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
564 }
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000566 virtual void ReadCounter(unsigned Value) {
567 Counter = Value;
568 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000569
570private:
571 void applyLangOptsToTarget() {
572 if (Target && InitializedLanguage) {
573 // Inform the target of the language options.
574 //
575 // FIXME: We shouldn't need to do this, the target should be immutable once
576 // created. This complexity should be lifted elsewhere.
577 Target->setForcedLangOptions(LangOpt);
578 }
579 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000580};
581
David Blaikie26e7a902011-09-26 00:01:39 +0000582class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000584
585public:
David Blaikie26e7a902011-09-26 00:01:39 +0000586 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000588 : StoredDiags(StoredDiags) { }
589
David Blaikied6471f72011-09-25 23:23:43 +0000590 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000591 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000592
593 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
594 // Just drop any diagnostics that come from cloned consumers; they'll
595 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000596 // FIXME: We'd like to be able to capture these somehow, even if it's just
597 // file/line/column, because they could occur when parsing module maps or
598 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000599 return new IgnoringDiagConsumer();
600 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000601};
602
603/// \brief RAII object that optionally captures diagnostics, if
604/// there is no diagnostic client to capture them already.
605class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000606 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000607 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000608 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000609
610public:
David Blaikied6471f72011-09-25 23:23:43 +0000611 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000612 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000613 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000614 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000615 if (RequestCapture || Diags.getClient() == 0) {
616 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000617 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000618 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000619 }
620
621 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000622 if (Diags.getClient() == &Client) {
623 Diags.takeClient();
624 Diags.setClient(PreviousClient);
625 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000626 }
627};
628
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000629} // anonymous namespace
630
David Blaikie26e7a902011-09-26 00:01:39 +0000631void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000632 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000633 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000634 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000635
Douglas Gregora88084b2010-02-18 18:08:43 +0000636 StoredDiags.push_back(StoredDiagnostic(Level, Info));
637}
638
Steve Naroff77accc12009-09-03 18:19:54 +0000639const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000640 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000641}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000642
Chris Lattner5f9e2722011-07-23 10:55:15 +0000643llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000644 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000645 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000646 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000647}
648
Douglas Gregore47be3e2010-11-11 00:39:14 +0000649/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000650void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000651 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000652 ASTUnit &AST, bool CaptureDiagnostics) {
653 if (!Diags.getPtr()) {
654 // No diagnostics engine was provided, so create our own diagnostics object
655 // with the default options.
656 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000657 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000658 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000659 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000660 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
661 ArgBegin, Client,
662 /*ShouldOwnClient=*/true,
663 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000665 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000666 }
667}
668
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000669ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000670 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000671 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000672 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000673 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000674 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000675 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000676 bool AllowPCHWithCompilerErrors,
677 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000678 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000679
680 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000681 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
682 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000683 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
684 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000685 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000686
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000687 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000688
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000689 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000690 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000691 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000692 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000693 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000694 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000695 AST->getFileManager(),
696 UserFilesAreVolatile);
Douglas Gregor8e238062011-11-11 00:35:06 +0000697 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000698 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000699 AST->ASTFileLangOpts,
700 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000701
Douglas Gregor4db64a42010-01-23 00:14:00 +0000702 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000703 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
704 if (const llvm::MemoryBuffer *
705 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
706 // Create the file entry for the file that we're mapping from.
707 const FileEntry *FromFile
708 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
709 memBuf->getBufferSize(),
710 0);
711 if (!FromFile) {
712 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
713 << RemappedFiles[I].first;
714 delete memBuf;
715 continue;
716 }
717
718 // Override the contents of the "from" file with the contents of
719 // the "to" file.
720 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
721
722 } else {
723 const char *fname = fileOrBuf.get<const char *>();
724 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
725 if (!ToFile) {
726 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
727 << RemappedFiles[I].first << fname;
728 continue;
729 }
730
731 // Create the file entry for the file that we're mapping from.
732 const FileEntry *FromFile
733 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
734 ToFile->getSize(),
735 0);
736 if (!FromFile) {
737 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
738 << RemappedFiles[I].first;
739 delete memBuf;
740 continue;
741 }
742
743 // Override the contents of the "from" file with the contents of
744 // the "to" file.
745 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000746 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000747 }
748
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000749 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000751 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000752 std::string Predefines;
753 unsigned Counter;
754
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000755 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000756
Douglas Gregor998b3d32011-09-01 23:39:15 +0000757 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
758 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
759 *AST,
760 /*IILookup=*/0,
761 /*OwnsHeaderSearch=*/false,
762 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000763 Preprocessor &PP = *AST->PP;
764
765 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
766 AST->getSourceManager(),
767 /*Target=*/0,
768 PP.getIdentifierTable(),
769 PP.getSelectorTable(),
770 PP.getBuiltinInfo(),
771 /* size_reserve = */0,
772 /*DelayInitialization=*/true);
773 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000774
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000775 Reader.reset(new ASTReader(PP, Context,
776 /*isysroot=*/"",
777 /*DisableValidation=*/false,
778 /*DisableStatCache=*/false,
779 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000780
781 // Recover resources if we crash before exiting this method.
782 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
783 ReaderCleanup(Reader.get());
784
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000785 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000786 AST->ASTFileLangOpts, HeaderInfo,
787 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000788
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000789 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000790 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000791 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000793 case ASTReader::Failure:
794 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000795 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000796 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000799 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
800
Daniel Dunbard5b61262009-09-21 03:03:47 +0000801 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000802 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000804 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000805 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000806 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000807 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000808 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000809
810 // Unregister the cleanup for ASTReader. It will get cleaned up
811 // by the ASTUnit cleanup.
812 ReaderCleanup.unregister();
813
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000814 Context.setExternalSource(Source);
815
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000816 // Create an AST consumer, even though it isn't used.
817 AST->Consumer.reset(new ASTConsumer);
818
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000819 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000820 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
821 AST->TheSema->Initialize();
822 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000823 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000824
Mike Stump1eb44332009-09-09 15:08:12 +0000825 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000826}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000827
828namespace {
829
Douglas Gregor9b7db622011-02-16 18:16:54 +0000830/// \brief Preprocessor callback class that updates a hash value with the names
831/// of all macros that have been defined by the translation unit.
832class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
833 unsigned &Hash;
834
835public:
836 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
837
838 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
839 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
840 }
841};
842
843/// \brief Add the given declaration to the hash of all top-level entities.
844void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
845 if (!D)
846 return;
847
848 DeclContext *DC = D->getDeclContext();
849 if (!DC)
850 return;
851
852 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
853 return;
854
855 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
856 if (ND->getIdentifier())
857 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
858 else if (DeclarationName Name = ND->getDeclName()) {
859 std::string NameStr = Name.getAsString();
860 Hash = llvm::HashString(NameStr, Hash);
861 }
862 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000863 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000864}
865
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000866class TopLevelDeclTrackerConsumer : public ASTConsumer {
867 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000868 unsigned &Hash;
869
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000870public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000871 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
872 : Unit(_Unit), Hash(Hash) {
873 Hash = 0;
874 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000875
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000876 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000877 if (!D)
878 return;
879
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000880 // FIXME: Currently ObjC method declarations are incorrectly being
881 // reported as top-level declarations, even though their DeclContext
882 // is the containing ObjC @interface/@implementation. This is a
883 // fundamental problem in the parser right now.
884 if (isa<ObjCMethodDecl>(D))
885 return;
886
887 AddTopLevelDeclarationToHash(D, Hash);
888 Unit.addTopLevelDecl(D);
889
890 handleFileLevelDecl(D);
891 }
892
893 void handleFileLevelDecl(Decl *D) {
894 Unit.addFileLevelDecl(D);
895 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
896 for (NamespaceDecl::decl_iterator
897 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
898 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000899 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000900 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000901
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000902 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000903 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
904 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000905 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000906 }
907
Sebastian Redl27372b42010-08-11 18:52:41 +0000908 // We're not interested in "interesting" decls.
909 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000910
911 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
912 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
913 handleTopLevelDecl(*it);
914 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000915};
916
917class TopLevelDeclTrackerAction : public ASTFrontendAction {
918public:
919 ASTUnit &Unit;
920
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000921 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000922 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000923 CI.getPreprocessor().addPPCallbacks(
924 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
925 return new TopLevelDeclTrackerConsumer(Unit,
926 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000927 }
928
929public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000930 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
931
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000932 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000933 virtual TranslationUnitKind getTranslationUnitKind() {
934 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000935 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000936};
937
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000938class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000939 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000940 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000941 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000942
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000943public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000944 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000945 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000946 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000947 Hash(Unit.getCurrentTopLevelHashValue()) {
948 Hash = 0;
949 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000950
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000951 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000952 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
953 Decl *D = *it;
954 // FIXME: Currently ObjC method declarations are incorrectly being
955 // reported as top-level declarations, even though their DeclContext
956 // is the containing ObjC @interface/@implementation. This is a
957 // fundamental problem in the parser right now.
958 if (isa<ObjCMethodDecl>(D))
959 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000960 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000961 TopLevelDecls.push_back(D);
962 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000963 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000964 }
965
966 virtual void HandleTranslationUnit(ASTContext &Ctx) {
967 PCHGenerator::HandleTranslationUnit(Ctx);
968 if (!Unit.getDiagnostics().hasErrorOccurred()) {
969 // Translate the top-level declarations we captured during
970 // parsing into declaration IDs in the precompiled
971 // preamble. This will allow us to deserialize those top-level
972 // declarations when requested.
973 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
974 Unit.addTopLevelDeclFromPreamble(
975 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000976 }
977 }
978};
979
980class PrecompilePreambleAction : public ASTFrontendAction {
981 ASTUnit &Unit;
982
983public:
984 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
985
986 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000987 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000988 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000989 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000990 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000991 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
992 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000993 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000994 return 0;
995
Douglas Gregor832d6202011-07-22 16:35:34 +0000996 if (!CI.getFrontendOpts().RelocatablePCH)
997 Sysroot.clear();
998
Douglas Gregor9b7db622011-02-16 18:16:54 +0000999 CI.getPreprocessor().addPPCallbacks(
1000 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001001 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1002 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001003 }
1004
1005 virtual bool hasCodeCompletionSupport() const { return false; }
1006 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001007 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001008};
1009
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001010}
1011
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001012static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1013 StoredDiagnostics) {
1014 // Get rid of stored diagnostics except the ones from the driver which do not
1015 // have a source location.
1016 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1017 if (StoredDiagnostics[I].getLocation().isValid()) {
1018 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1019 --I;
1020 }
1021 }
1022}
1023
1024static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1025 StoredDiagnostics,
1026 SourceManager &SM) {
1027 // The stored diagnostic has the old source manager in it; update
1028 // the locations to refer into the new source manager. Since we've
1029 // been careful to make sure that the source manager's state
1030 // before and after are identical, so that we can reuse the source
1031 // location itself.
1032 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1033 if (StoredDiagnostics[I].getLocation().isValid()) {
1034 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1035 StoredDiagnostics[I].setLocation(Loc);
1036 }
1037 }
1038}
1039
Douglas Gregorabc563f2010-07-19 21:46:24 +00001040/// Parse the source file into a translation unit using the given compiler
1041/// invocation, replacing the current translation unit.
1042///
1043/// \returns True if a failure occurred that causes the ASTUnit not to
1044/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001045bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001046 delete SavedMainFileBuffer;
1047 SavedMainFileBuffer = 0;
1048
Ted Kremenek4f327862011-03-21 18:40:17 +00001049 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001050 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001051 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001052 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001053
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001054 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001055 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001056
1057 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001058 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1059 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001060
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001061 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001062 CCInvocation(new CompilerInvocation(*Invocation));
1063
1064 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001065 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001066
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001067 // Set up diagnostics, capturing any diagnostics that would
1068 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001069 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001070
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001071 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001072 Clang->getTargetOpts().Features = TargetFeatures;
1073 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001074 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001075 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001076 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001077 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001078 }
1079
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001080 // Inform the target of the language options.
1081 //
1082 // FIXME: We shouldn't need to do this, the target should be immutable once
1083 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001084 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001085
Ted Kremenek03201fb2011-03-21 18:40:07 +00001086 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001087 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001088 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001089 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001090 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001091 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092
Douglas Gregorabc563f2010-07-19 21:46:24 +00001093 // Configure the various subsystems.
1094 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001095 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001097 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001098 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1099 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001100 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001101 Ctx = 0;
1102 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001103 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001104
1105 // Clear out old caches and data.
1106 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001107 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001108 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001109
Douglas Gregorf128fed2010-08-20 00:02:33 +00001110 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001111 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001112 TopLevelDeclsInPreamble.clear();
1113 }
1114
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001115 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001116 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001117
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001118 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001119 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001121 // If the main file has been overridden due to the use of a preamble,
1122 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001123 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001124 if (OverrideMainBuffer) {
1125 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1126 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1127 PreprocessorOpts.PrecompiledPreambleBytes.second
1128 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001129 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001130 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001131
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001132 // The stored diagnostic has the old source manager in it; update
1133 // the locations to refer into the new source manager. Since we've
1134 // been careful to make sure that the source manager's state
1135 // before and after are identical, so that we can reuse the source
1136 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001137 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001138
1139 // Keep track of the override buffer;
1140 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001141 }
1142
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001143 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001144 new TopLevelDeclTrackerAction(*this));
1145
1146 // Recover resources if we crash before exiting this method.
1147 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1148 ActCleanup(Act.get());
1149
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001150 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001151 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001152
1153 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001154 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001155 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1156 getSourceManager(), PreambleDiagnostics,
1157 StoredDiagnostics);
1158 }
1159
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001160 if (!Act->Execute())
1161 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001162
1163 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001164
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001165 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001166
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001167 FailedParseDiagnostics.clear();
1168
Douglas Gregorabc563f2010-07-19 21:46:24 +00001169 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001170
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001171error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001172 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001173 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001174 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001175 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001176 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001177
1178 // Keep the ownership of the data in the ASTUnit because the client may
1179 // want to see the diagnostics.
1180 transferASTDataFromCompilerInstance(*Clang);
1181 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001182 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001183 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001184 return true;
1185}
1186
Douglas Gregor44c181a2010-07-23 00:33:23 +00001187/// \brief Simple function to retrieve a path for a preamble precompiled header.
1188static std::string GetPreamblePCHPath() {
1189 // FIXME: This is lame; sys::Path should provide this function (in particular,
1190 // it should know how to find the temporary files dir).
1191 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001192 // FIXME: This is a hack so that we can override the preamble file during
1193 // crash-recovery testing, which is the only case where the preamble files
1194 // are not necessarily cleaned up.
1195 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1196 if (TmpFile)
1197 return TmpFile;
1198
Douglas Gregor44c181a2010-07-23 00:33:23 +00001199 std::string Error;
1200 const char *TmpDir = ::getenv("TMPDIR");
1201 if (!TmpDir)
1202 TmpDir = ::getenv("TEMP");
1203 if (!TmpDir)
1204 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001205#ifdef LLVM_ON_WIN32
1206 if (!TmpDir)
1207 TmpDir = ::getenv("USERPROFILE");
1208#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001209 if (!TmpDir)
1210 TmpDir = "/tmp";
1211 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001212 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001213 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001214 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001215 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 return std::string();
1217
Douglas Gregor44c181a2010-07-23 00:33:23 +00001218 return P.str();
1219}
1220
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001221/// \brief Compute the preamble for the main file, providing the source buffer
1222/// that corresponds to the main file along with a pair (bytes, start-of-line)
1223/// that describes the preamble.
1224std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001225ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1226 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001227 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001228 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001229 CreatedBuffer = false;
1230
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 // Try to determine if the main file has been remapped, either from the
1232 // command line (to another file) or directly through the compiler invocation
1233 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001234 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001235 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1237 // Check whether there is a file-file remapping of the main file
1238 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001239 M = PreprocessorOpts.remapped_file_begin(),
1240 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 M != E;
1242 ++M) {
1243 llvm::sys::PathWithStatus MPath(M->first);
1244 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1245 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1246 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001247 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001248 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 CreatedBuffer = false;
1250 }
1251
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001252 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001254 return std::make_pair((llvm::MemoryBuffer*)0,
1255 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 }
1258 }
1259 }
1260
1261 // Check whether there is a file-buffer remapping. It supercedes the
1262 // file-file remapping.
1263 for (PreprocessorOptions::remapped_file_buffer_iterator
1264 M = PreprocessorOpts.remapped_file_buffer_begin(),
1265 E = PreprocessorOpts.remapped_file_buffer_end();
1266 M != E;
1267 ++M) {
1268 llvm::sys::PathWithStatus MPath(M->first);
1269 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1270 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1271 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001272 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001273 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001274 CreatedBuffer = false;
1275 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001276
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001278 }
1279 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001280 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 }
1282
1283 // If the main source file was not remapped, load it now.
1284 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001285 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001287 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001288
1289 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 }
1291
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001292 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001293 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001294 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001295}
1296
Douglas Gregor754f3492010-07-24 00:38:13 +00001297static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001298 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001299 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001300 llvm::MemoryBuffer *Result
1301 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1302 memcpy(const_cast<char*>(Result->getBufferStart()),
1303 Old->getBufferStart(), Old->getBufferSize());
1304 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001305 ' ', NewSize - Old->getBufferSize() - 1);
1306 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001307
Douglas Gregor754f3492010-07-24 00:38:13 +00001308 return Result;
1309}
1310
Douglas Gregor175c4a92010-07-23 23:58:40 +00001311/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1312/// the source file.
1313///
1314/// This routine will compute the preamble of the main source file. If a
1315/// non-trivial preamble is found, it will precompile that preamble into a
1316/// precompiled header so that the precompiled preamble can be used to reduce
1317/// reparsing time. If a precompiled preamble has already been constructed,
1318/// this routine will determine if it is still valid and, if so, avoid
1319/// rebuilding the precompiled preamble.
1320///
Douglas Gregordf95a132010-08-09 20:45:32 +00001321/// \param AllowRebuild When true (the default), this routine is
1322/// allowed to rebuild the precompiled preamble if it is found to be
1323/// out-of-date.
1324///
1325/// \param MaxLines When non-zero, the maximum number of lines that
1326/// can occur within the preamble.
1327///
Douglas Gregor754f3492010-07-24 00:38:13 +00001328/// \returns If the precompiled preamble can be used, returns a newly-allocated
1329/// buffer that should be used in place of the main file when doing so.
1330/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001331llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001332 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001333 bool AllowRebuild,
1334 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001335
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001336 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001337 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1338 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001339 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001340 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001341
1342 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001343 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001344 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001345
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001346 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001347 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001348 if (CreatedPreambleBuffer)
1349 OwnedPreambleBuffer.reset(NewPreamble.first);
1350
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001351 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001352 // We couldn't find a preamble in the main source. Clear out the current
1353 // preamble, if we have one. It's obviously no good any more.
1354 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001355 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001356
1357 // The next time we actually see a preamble, precompile it.
1358 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001359 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001360 }
1361
1362 if (!Preamble.empty()) {
1363 // We've previously computed a preamble. Check whether we have the same
1364 // preamble now that we did before, and that there's enough space in
1365 // the main-file buffer within the precompiled preamble to fit the
1366 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001367 if (Preamble.size() == NewPreamble.second.first &&
1368 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001369 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001370 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001371 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001372 // The preamble has not changed. We may be able to re-use the precompiled
1373 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001374
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001375 // Check that none of the files used by the preamble have changed.
1376 bool AnyFileChanged = false;
1377
1378 // First, make a record of those files that have been overridden via
1379 // remapping or unsaved_files.
1380 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1381 for (PreprocessorOptions::remapped_file_iterator
1382 R = PreprocessorOpts.remapped_file_begin(),
1383 REnd = PreprocessorOpts.remapped_file_end();
1384 !AnyFileChanged && R != REnd;
1385 ++R) {
1386 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001387 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001388 // If we can't stat the file we're remapping to, assume that something
1389 // horrible happened.
1390 AnyFileChanged = true;
1391 break;
1392 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001393
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001394 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1395 StatBuf.st_mtime);
1396 }
1397 for (PreprocessorOptions::remapped_file_buffer_iterator
1398 R = PreprocessorOpts.remapped_file_buffer_begin(),
1399 REnd = PreprocessorOpts.remapped_file_buffer_end();
1400 !AnyFileChanged && R != REnd;
1401 ++R) {
1402 // FIXME: Should we actually compare the contents of file->buffer
1403 // remappings?
1404 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1405 0);
1406 }
1407
1408 // Check whether anything has changed.
1409 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1410 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1411 !AnyFileChanged && F != FEnd;
1412 ++F) {
1413 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1414 = OverriddenFiles.find(F->first());
1415 if (Overridden != OverriddenFiles.end()) {
1416 // This file was remapped; check whether the newly-mapped file
1417 // matches up with the previous mapping.
1418 if (Overridden->second != F->second)
1419 AnyFileChanged = true;
1420 continue;
1421 }
1422
1423 // The file was not remapped; check whether it has changed on disk.
1424 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001425 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001426 // If we can't stat the file, assume that something horrible happened.
1427 AnyFileChanged = true;
1428 } else if (StatBuf.st_size != F->second.first ||
1429 StatBuf.st_mtime != F->second.second)
1430 AnyFileChanged = true;
1431 }
1432
1433 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001434 // Okay! We can re-use the precompiled preamble.
1435
1436 // Set the state of the diagnostic object to mimic its state
1437 // after parsing the preamble.
1438 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001439 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001440 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001441 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001442
1443 // Create a version of the main file buffer that is padded to
1444 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001445 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001446 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001447 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001448 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001449 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001450
1451 // If we aren't allowed to rebuild the precompiled preamble, just
1452 // return now.
1453 if (!AllowRebuild)
1454 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001455
Douglas Gregor175c4a92010-07-23 23:58:40 +00001456 // We can't reuse the previously-computed preamble. Build a new one.
1457 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001458 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001459 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001460 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001461 } else if (!AllowRebuild) {
1462 // We aren't allowed to rebuild the precompiled preamble; just
1463 // return now.
1464 return 0;
1465 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001466
1467 // If the preamble rebuild counter > 1, it's because we previously
1468 // failed to build a preamble and we're not yet ready to try
1469 // again. Decrement the counter and return a failure.
1470 if (PreambleRebuildCounter > 1) {
1471 --PreambleRebuildCounter;
1472 return 0;
1473 }
1474
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001475 // Create a temporary file for the precompiled preamble. In rare
1476 // circumstances, this can fail.
1477 std::string PreamblePCHPath = GetPreamblePCHPath();
1478 if (PreamblePCHPath.empty()) {
1479 // Try again next time.
1480 PreambleRebuildCounter = 1;
1481 return 0;
1482 }
1483
Douglas Gregor175c4a92010-07-23 23:58:40 +00001484 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001485 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001486 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001487
1488 // Create a new buffer that stores the preamble. The buffer also contains
1489 // extra space for the original contents of the file (which will be present
1490 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001491 // grows.
1492 PreambleReservedSize = NewPreamble.first->getBufferSize();
1493 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001494 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001496 PreambleReservedSize *= 2;
1497
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001498 // Save the preamble text for later; we'll need to compare against it for
1499 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001500 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001501 Preamble.assign(FileMgr->getFile(MainFilename),
1502 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001503 NewPreamble.first->getBufferStart()
1504 + NewPreamble.second.first);
1505 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1506
Douglas Gregor671947b2010-08-19 01:33:06 +00001507 delete PreambleBuffer;
1508 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001509 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001510 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001511 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001512 NewPreamble.first->getBufferStart(), Preamble.size());
1513 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001514 ' ', PreambleReservedSize - Preamble.size() - 1);
1515 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
1517 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001518 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001519 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1520
1521 // Tell the compiler invocation to generate a temporary precompiled header.
1522 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001523 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001524 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001525 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1526 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001527
1528 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001529 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001530
1531 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001532 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1533 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001534
Douglas Gregor01b6e312011-07-01 18:22:13 +00001535 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001536 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001538 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540
1541 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001542 Clang->getTargetOpts().Features = TargetFeatures;
1543 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1544 Clang->getTargetOpts()));
1545 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001546 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1547 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001548 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001549 PreprocessorOpts.eraseRemappedFile(
1550 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001551 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552 }
1553
1554 // Inform the target of the language options.
1555 //
1556 // FIXME: We shouldn't need to do this, the target should be immutable once
1557 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001558 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001559
Ted Kremenek03201fb2011-03-21 18:40:07 +00001560 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001561 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001562 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001563 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001564 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001565 "IR inputs not support here!");
1566
1567 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001568 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001570 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001571 TopLevelDecls.clear();
1572 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573
1574 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001575 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001576
1577 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001578 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001579 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001580
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001581 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001582 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001583 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001584 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1585 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001586 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001587 PreprocessorOpts.eraseRemappedFile(
1588 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001589 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 }
1591
1592 Act->Execute();
1593 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001594
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001595 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001596 // There were errors parsing the preamble, so no precompiled header was
1597 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001598 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001599 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1600 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001601 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001602 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001603 PreprocessorOpts.eraseRemappedFile(
1604 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001605 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001606 }
1607
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001608 // Transfer any diagnostics generated when parsing the preamble into the set
1609 // of preamble diagnostics.
1610 PreambleDiagnostics.clear();
1611 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001612 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001613 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001614
Douglas Gregor175c4a92010-07-23 23:58:40 +00001615 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001616 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001617 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001618
1619 // Keep track of all of the files that the source manager knows about,
1620 // so we can verify whether they have changed or not.
1621 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001622 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001623 const llvm::MemoryBuffer *MainFileBuffer
1624 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1625 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1626 FEnd = SourceMgr.fileinfo_end();
1627 F != FEnd;
1628 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001629 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001630 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1631 continue;
1632
1633 FilesInPreamble[File->getName()]
1634 = std::make_pair(F->second->getSize(), File->getModificationTime());
1635 }
1636
Douglas Gregoreababfb2010-08-04 05:53:38 +00001637 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001638 PreprocessorOpts.eraseRemappedFile(
1639 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001640
1641 // If the hash of top-level entities differs from the hash of the top-level
1642 // entities the last time we rebuilt the preamble, clear out the completion
1643 // cache.
1644 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1645 CompletionCacheTopLevelHashValue = 0;
1646 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1647 }
1648
Douglas Gregor754f3492010-07-24 00:38:13 +00001649 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001650 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001651 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001652}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001653
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001654void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1655 std::vector<Decl *> Resolved;
1656 Resolved.reserve(TopLevelDeclsInPreamble.size());
1657 ExternalASTSource &Source = *getASTContext().getExternalSource();
1658 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1659 // Resolve the declaration ID to an actual declaration, possibly
1660 // deserializing the declaration in the process.
1661 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1662 if (D)
1663 Resolved.push_back(D);
1664 }
1665 TopLevelDeclsInPreamble.clear();
1666 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1667}
1668
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001669void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1670 // Steal the created target, context, and preprocessor.
1671 TheSema.reset(CI.takeSema());
1672 Consumer.reset(CI.takeASTConsumer());
1673 Ctx = &CI.getASTContext();
1674 PP = &CI.getPreprocessor();
1675 CI.setSourceManager(0);
1676 CI.setFileManager(0);
1677 Target = &CI.getTarget();
1678 Reader = CI.getModuleManager();
1679}
1680
Chris Lattner5f9e2722011-07-23 10:55:15 +00001681StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001682 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001683}
1684
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001685ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001686 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001687 bool CaptureDiagnostics,
1688 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001689 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001690 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001691 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001692 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001693 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001694 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001695 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001696 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1697 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1698 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001699
1700 return AST.take();
1701}
1702
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001703ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001704 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001705 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001706 ASTUnit *Unit,
1707 bool Persistent,
1708 StringRef ResourceFilesPath,
1709 bool OnlyLocalDecls,
1710 bool CaptureDiagnostics,
1711 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001712 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001713 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001714 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001715 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001716 assert(CI && "A CompilerInvocation is required");
1717
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001718 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001719 ASTUnit *AST = Unit;
1720 if (!AST) {
1721 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001722 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001723 AST = OwnAST.get();
1724 }
1725
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001726 if (!ResourceFilesPath.empty()) {
1727 // Override the resources path.
1728 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1729 }
1730 AST->OnlyLocalDecls = OnlyLocalDecls;
1731 AST->CaptureDiagnostics = CaptureDiagnostics;
1732 if (PrecompilePreamble)
1733 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001734 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001735 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001736 AST->IncludeBriefCommentsInCodeCompletion
1737 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001738
1739 // Recover resources if we crash before exiting this method.
1740 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001741 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001742 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1743 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001744 DiagCleanup(Diags.getPtr());
1745
1746 // We'll manage file buffers ourselves.
1747 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1748 CI->getFrontendOpts().DisableFree = false;
1749 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1750
1751 // Save the target features.
1752 AST->TargetFeatures = CI->getTargetOpts().Features;
1753
1754 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001755 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001756
1757 // Recover resources if we crash before exiting this method.
1758 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1759 CICleanup(Clang.get());
1760
1761 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001762 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001763
1764 // Set up diagnostics, capturing any diagnostics that would
1765 // otherwise be dropped.
1766 Clang->setDiagnostics(&AST->getDiagnostics());
1767
1768 // Create the target instance.
1769 Clang->getTargetOpts().Features = AST->TargetFeatures;
1770 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1771 Clang->getTargetOpts()));
1772 if (!Clang->hasTarget())
1773 return 0;
1774
1775 // Inform the target of the language options.
1776 //
1777 // FIXME: We shouldn't need to do this, the target should be immutable once
1778 // created. This complexity should be lifted elsewhere.
1779 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1780
1781 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1782 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001783 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001784 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001785 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001786 "IR inputs not supported here!");
1787
1788 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 AST->TheSema.reset();
1790 AST->Ctx = 0;
1791 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001792 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001793
1794 // Create a file manager object to provide access to and cache the filesystem.
1795 Clang->setFileManager(&AST->getFileManager());
1796
1797 // Create the source manager.
1798 Clang->setSourceManager(&AST->getSourceManager());
1799
1800 ASTFrontendAction *Act = Action;
1801
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001802 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001803 if (!Act) {
1804 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1805 Act = TrackerAct.get();
1806 }
1807
1808 // Recover resources if we crash before exiting this method.
1809 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1810 ActCleanup(TrackerAct.get());
1811
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001812 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1813 AST->transferASTDataFromCompilerInstance(*Clang);
1814 if (OwnAST && ErrAST)
1815 ErrAST->swap(OwnAST);
1816
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001817 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001818 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001819
1820 if (Persistent && !TrackerAct) {
1821 Clang->getPreprocessor().addPPCallbacks(
1822 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1823 std::vector<ASTConsumer*> Consumers;
1824 if (Clang->hasASTConsumer())
1825 Consumers.push_back(Clang->takeASTConsumer());
1826 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1827 AST->getCurrentTopLevelHashValue()));
1828 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1829 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001830 if (!Act->Execute()) {
1831 AST->transferASTDataFromCompilerInstance(*Clang);
1832 if (OwnAST && ErrAST)
1833 ErrAST->swap(OwnAST);
1834
1835 return 0;
1836 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001837
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001838 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001839 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001840
1841 Act->EndSourceFile();
1842
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001843 if (OwnAST)
1844 return OwnAST.take();
1845 else
1846 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001847}
1848
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001849bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1850 if (!Invocation)
1851 return true;
1852
1853 // We'll manage file buffers ourselves.
1854 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1855 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001856 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001857
Douglas Gregor1aa27302011-01-27 18:02:58 +00001858 // Save the target features.
1859 TargetFeatures = Invocation->getTargetOpts().Features;
1860
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001861 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001862 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001863 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001864 OverrideMainBuffer
1865 = getMainBufferWithPrecompiledPreamble(*Invocation);
1866 }
1867
Douglas Gregor213f18b2010-10-28 15:44:59 +00001868 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001869 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001870
Ted Kremenek25a11e12011-03-22 01:15:24 +00001871 // Recover resources if we crash before exiting this method.
1872 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1873 MemBufferCleanup(OverrideMainBuffer);
1874
Douglas Gregor213f18b2010-10-28 15:44:59 +00001875 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001876}
1877
Douglas Gregorabc563f2010-07-19 21:46:24 +00001878ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001879 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001880 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001881 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001882 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001883 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001884 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001885 bool IncludeBriefCommentsInCodeCompletion,
1886 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001887 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001888 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001889 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001890 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001891 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001892 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001893 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001894 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001895 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001896 AST->IncludeBriefCommentsInCodeCompletion
1897 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001898 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001899 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001900
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001901 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001902 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1903 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001904 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1905 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001906 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001907
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001908 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001909}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001910
1911ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1912 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001913 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001914 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001915 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001916 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001917 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001918 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001919 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001920 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001921 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001922 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001923 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001924 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001925 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001926 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001927 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001928 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001929 // No diagnostics engine was provided, so create our own diagnostics object
1930 // with the default options.
1931 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001932 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1933 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001934 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001935
Chris Lattner5f9e2722011-07-23 10:55:15 +00001936 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001937
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001938 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001939
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001940 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001941
Douglas Gregore47be3e2010-11-11 00:39:14 +00001942 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001943 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001944
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001945 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001946 llvm::makeArrayRef(ArgBegin, ArgEnd),
1947 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001948 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001949 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001950 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001951
Douglas Gregor4db64a42010-01-23 00:14:00 +00001952 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001953 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1954 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1955 if (const llvm::MemoryBuffer *
1956 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1957 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1958 } else {
1959 const char *fname = fileOrBuf.get<const char *>();
1960 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1961 }
1962 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001963 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1964 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1965 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001966
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001967 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001968 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001969
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001970 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1971
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001972 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001973 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001974 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001975 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001976 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001977 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001978 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001979 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001980 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001981 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001982 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001983 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001984 AST->IncludeBriefCommentsInCodeCompletion
1985 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001986 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001987 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001988 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001989 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001990 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001991
1992 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001993 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1994 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001995
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001996 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1997 // Some error occurred, if caller wants to examine diagnostics, pass it the
1998 // ASTUnit.
1999 if (ErrAST) {
2000 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2001 ErrAST->swap(AST);
2002 }
2003 return 0;
2004 }
2005
2006 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002007}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002008
2009bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002010 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002011 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002012
2013 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002014
Douglas Gregor213f18b2010-10-28 15:44:59 +00002015 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002016 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002017
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002018 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002019 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002020 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002021 for (PreprocessorOptions::remapped_file_buffer_iterator
2022 R = PPOpts.remapped_file_buffer_begin(),
2023 REnd = PPOpts.remapped_file_buffer_end();
2024 R != REnd;
2025 ++R) {
2026 delete R->second;
2027 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002028 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002029 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2030 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2031 if (const llvm::MemoryBuffer *
2032 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2033 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2034 memBuf);
2035 } else {
2036 const char *fname = fileOrBuf.get<const char *>();
2037 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2038 fname);
2039 }
2040 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002041
Douglas Gregoreababfb2010-08-04 05:53:38 +00002042 // If we have a preamble file lying around, or if we might try to
2043 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002044 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002045 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002046 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002047
Douglas Gregorabc563f2010-07-19 21:46:24 +00002048 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002049 getDiagnostics().Reset();
2050 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002051 if (OverrideMainBuffer)
2052 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002053
Douglas Gregor175c4a92010-07-23 23:58:40 +00002054 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002055 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002056
2057 // If we're caching global code-completion results, and the top-level
2058 // declarations have changed, clear out the code-completion cache.
2059 if (!Result && ShouldCacheCodeCompletionResults &&
2060 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2061 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002062
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002063 // We now need to clear out the completion info related to this translation
2064 // unit; it'll be recreated if necessary.
2065 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002066
Douglas Gregor175c4a92010-07-23 23:58:40 +00002067 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002068}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002069
Douglas Gregor87c08a52010-08-13 22:48:40 +00002070//----------------------------------------------------------------------------//
2071// Code completion
2072//----------------------------------------------------------------------------//
2073
2074namespace {
2075 /// \brief Code completion consumer that combines the cached code-completion
2076 /// results from an ASTUnit with the code-completion results provided to it,
2077 /// then passes the result on to
2078 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002079 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002080 ASTUnit &AST;
2081 CodeCompleteConsumer &Next;
2082
2083 public:
2084 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002085 const CodeCompleteOptions &CodeCompleteOpts)
2086 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2087 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002088 {
2089 // Compute the set of contexts in which we will look when we don't have
2090 // any information about the specific context.
2091 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002092 = (1LL << CodeCompletionContext::CCC_TopLevel)
2093 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2094 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2095 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2096 | (1LL << CodeCompletionContext::CCC_Statement)
2097 | (1LL << CodeCompletionContext::CCC_Expression)
2098 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2099 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2100 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2101 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2102 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2103 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2104 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002105
David Blaikie4e4d0842012-03-11 07:00:24 +00002106 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002107 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2108 | (1LL << CodeCompletionContext::CCC_UnionTag)
2109 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002110 }
2111
2112 virtual void ProcessCodeCompleteResults(Sema &S,
2113 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002114 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002115 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002116
2117 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2118 OverloadCandidate *Candidates,
2119 unsigned NumCandidates) {
2120 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2121 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002122
Douglas Gregordae68752011-02-01 22:57:45 +00002123 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002124 return Next.getAllocator();
2125 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002126
2127 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2128 return Next.getCodeCompletionTUInfo();
2129 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002130 };
2131}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002132
Douglas Gregor5f808c22010-08-16 21:18:39 +00002133/// \brief Helper function that computes which global names are hidden by the
2134/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002135static void CalculateHiddenNames(const CodeCompletionContext &Context,
2136 CodeCompletionResult *Results,
2137 unsigned NumResults,
2138 ASTContext &Ctx,
2139 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002140 bool OnlyTagNames = false;
2141 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002142 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002143 case CodeCompletionContext::CCC_TopLevel:
2144 case CodeCompletionContext::CCC_ObjCInterface:
2145 case CodeCompletionContext::CCC_ObjCImplementation:
2146 case CodeCompletionContext::CCC_ObjCIvarList:
2147 case CodeCompletionContext::CCC_ClassStructUnion:
2148 case CodeCompletionContext::CCC_Statement:
2149 case CodeCompletionContext::CCC_Expression:
2150 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002151 case CodeCompletionContext::CCC_DotMemberAccess:
2152 case CodeCompletionContext::CCC_ArrowMemberAccess:
2153 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002154 case CodeCompletionContext::CCC_Namespace:
2155 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002156 case CodeCompletionContext::CCC_Name:
2157 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002158 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002159 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002160 break;
2161
2162 case CodeCompletionContext::CCC_EnumTag:
2163 case CodeCompletionContext::CCC_UnionTag:
2164 case CodeCompletionContext::CCC_ClassOrStructTag:
2165 OnlyTagNames = true;
2166 break;
2167
2168 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002169 case CodeCompletionContext::CCC_MacroName:
2170 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002171 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002172 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002173 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002174 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002175 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002176 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002177 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002178 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2179 case CodeCompletionContext::CCC_ObjCClassMessage:
2180 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002181 // We're looking for nothing, or we're looking for names that cannot
2182 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002183 return;
2184 }
2185
John McCall0a2c5e22010-08-25 06:19:51 +00002186 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187 for (unsigned I = 0; I != NumResults; ++I) {
2188 if (Results[I].Kind != Result::RK_Declaration)
2189 continue;
2190
2191 unsigned IDNS
2192 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2193
2194 bool Hiding = false;
2195 if (OnlyTagNames)
2196 Hiding = (IDNS & Decl::IDNS_Tag);
2197 else {
2198 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002199 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2200 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002201 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002202 HiddenIDNS |= Decl::IDNS_Tag;
2203 Hiding = (IDNS & HiddenIDNS);
2204 }
2205
2206 if (!Hiding)
2207 continue;
2208
2209 DeclarationName Name = Results[I].Declaration->getDeclName();
2210 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2211 HiddenNames.insert(Identifier->getName());
2212 else
2213 HiddenNames.insert(Name.getAsString());
2214 }
2215}
2216
2217
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002218void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2219 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002220 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002221 unsigned NumResults) {
2222 // Merge the results we were given with the results we cached.
2223 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002224 uint64_t InContexts =
2225 Context.getKind() == CodeCompletionContext::CCC_Recovery
2226 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002227 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002228 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002229 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002230 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002231 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002232 C = AST.cached_completion_begin(),
2233 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002234 C != CEnd; ++C) {
2235 // If the context we are in matches any of the contexts we are
2236 // interested in, we'll add this result.
2237 if ((C->ShowInContexts & InContexts) == 0)
2238 continue;
2239
2240 // If we haven't added any results previously, do so now.
2241 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002242 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2243 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002244 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2245 AddedResult = true;
2246 }
2247
Douglas Gregor5f808c22010-08-16 21:18:39 +00002248 // Determine whether this global completion result is hidden by a local
2249 // completion result. If so, skip it.
2250 if (C->Kind != CXCursor_MacroDefinition &&
2251 HiddenNames.count(C->Completion->getTypedText()))
2252 continue;
2253
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002254 // Adjust priority based on similar type classes.
2255 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002256 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002257 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002258 if (!Context.getPreferredType().isNull()) {
2259 if (C->Kind == CXCursor_MacroDefinition) {
2260 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002261 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002262 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002263 } else if (C->Type) {
2264 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002265 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002266 Context.getPreferredType().getUnqualifiedType());
2267 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2268 if (ExpectedSTC == C->TypeClass) {
2269 // We know this type is similar; check for an exact match.
2270 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002271 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002272 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002273 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002274 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2275 Priority /= CCF_ExactTypeMatch;
2276 else
2277 Priority /= CCF_SimilarTypeMatch;
2278 }
2279 }
2280 }
2281
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002282 // Adjust the completion string, if required.
2283 if (C->Kind == CXCursor_MacroDefinition &&
2284 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2285 // Create a new code-completion string that just contains the
2286 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002287 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2288 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002289 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002290 CursorKind = CXCursor_NotImplemented;
2291 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002292 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002293 }
2294
Douglas Gregor4125c372010-08-25 18:03:13 +00002295 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002296 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002297 }
2298
2299 // If we did not add any cached completion results, just forward the
2300 // results we were given to the next consumer.
2301 if (!AddedResult) {
2302 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2303 return;
2304 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002305
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002306 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2307 AllResults.size());
2308}
2309
2310
2311
Chris Lattner5f9e2722011-07-23 10:55:15 +00002312void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002313 RemappedFile *RemappedFiles,
2314 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002315 bool IncludeMacros,
2316 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002317 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002318 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002319 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002320 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002321 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2322 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002323 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002324 return;
2325
Douglas Gregor213f18b2010-10-28 15:44:59 +00002326 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002327 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002328 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002329
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002330 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002331 CCInvocation(new CompilerInvocation(*Invocation));
2332
2333 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002334 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002335 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002336
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002337 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2338 CachedCompletionResults.empty();
2339 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2340 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2341 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2342
2343 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2344
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002345 FrontendOpts.CodeCompletionAt.FileName = File;
2346 FrontendOpts.CodeCompletionAt.Line = Line;
2347 FrontendOpts.CodeCompletionAt.Column = Column;
2348
2349 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002350 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002351
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002352 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002353
2354 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002355 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2356 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002357
Ted Kremenek4f327862011-03-21 18:40:17 +00002358 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002359 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002360
2361 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002362 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002363 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002364 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002365 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002366 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367
2368 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002369 Clang->getTargetOpts().Features = TargetFeatures;
2370 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2371 Clang->getTargetOpts()));
2372 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002373 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002374 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 }
2376
2377 // Inform the target of the language options.
2378 //
2379 // FIXME: We shouldn't need to do this, the target should be immutable once
2380 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002381 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382
Ted Kremenek03201fb2011-03-21 18:40:07 +00002383 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002384 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002385 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002386 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002387 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002388 "IR inputs not support here!");
2389
2390
2391 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002392 Clang->setFileManager(&FileMgr);
2393 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002394
2395 // Remap files.
2396 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002397 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002398 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002399 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2400 if (const llvm::MemoryBuffer *
2401 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2402 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2403 OwnedBuffers.push_back(memBuf);
2404 } else {
2405 const char *fname = fileOrBuf.get<const char *>();
2406 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2407 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002408 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409
Douglas Gregor87c08a52010-08-13 22:48:40 +00002410 // Use the code completion consumer we were given, but adding any cached
2411 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002412 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002413 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002414 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002415
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002416 Clang->getFrontendOpts().SkipFunctionBodies = true;
2417
Douglas Gregordf95a132010-08-09 20:45:32 +00002418 // If we have a precompiled preamble, try to use it. We only allow
2419 // the use of the precompiled preamble if we're if the completion
2420 // point is within the main file, after the end of the precompiled
2421 // preamble.
2422 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002423 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002424 using llvm::sys::FileStatus;
2425 llvm::sys::PathWithStatus CompleteFilePath(File);
2426 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2427 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2428 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002429 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2430 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002431 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002432 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002433 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002434 }
2435
2436 // If the main file has been overridden due to the use of a preamble,
2437 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002438 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002439 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002440 stored_diag_begin(),
2441 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002442 if (OverrideMainBuffer) {
2443 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2444 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2445 PreprocessorOpts.PrecompiledPreambleBytes.second
2446 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002447 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002448 PreprocessorOpts.DisablePCHValidation = true;
2449
Douglas Gregor2283d792010-08-20 00:59:43 +00002450 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002451 } else {
2452 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2453 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002454 }
2455
Douglas Gregordca8ee82011-05-06 16:33:08 +00002456 // Disable the preprocessing record
2457 PreprocessorOpts.DetailedRecord = false;
2458
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002459 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002460 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002461 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002462 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002463 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002464 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2465 getSourceManager(), PreambleDiagnostics,
2466 StoredDiagnostics);
2467 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002468 Act->Execute();
2469 Act->EndSourceFile();
2470 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002471
2472 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002473}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002474
Chris Lattner5f9e2722011-07-23 10:55:15 +00002475CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002476 // Write to a temporary file and later rename it to the actual file, to avoid
2477 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002478 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002479 TempPath = File;
2480 TempPath += "-%%%%%%%%";
2481 int fd;
2482 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2483 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002484 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002485
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002486 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2487 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002488 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002489
2490 serialize(Out);
2491 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002492 if (Out.has_error()) {
2493 Out.clear_error();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002494 return CXSaveError_Unknown;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002495 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002496
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002497 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002498 bool exists;
2499 llvm::sys::fs::remove(TempPath.str(), exists);
2500 return CXSaveError_Unknown;
2501 }
2502
2503 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002504}
2505
Chris Lattner5f9e2722011-07-23 10:55:15 +00002506bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002507 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002508
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002509 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002510 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002511 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002512 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002513 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002514
2515 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002516 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002517 OS.write((char *)&Buffer.front(), Buffer.size());
2518
2519 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002520}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002521
2522typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2523
2524static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2525 unsigned Raw = L.getRawEncoding();
2526 const unsigned MacroBit = 1U << 31;
2527 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2528 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2529}
2530
2531void ASTUnit::TranslateStoredDiagnostics(
2532 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002533 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002534 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002535 const SmallVectorImpl<StoredDiagnostic> &Diags,
2536 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002537 // The stored diagnostic has the old source manager in it; update
2538 // the locations to refer into the new source manager. We also need to remap
2539 // all the locations to the new view. This includes the diag location, any
2540 // associated source ranges, and the source ranges of associated fix-its.
2541 // FIXME: There should be a cleaner way to do this.
2542
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002544 Result.reserve(Diags.size());
2545 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002546 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002547 assert(Mod && "Don't have preamble module");
2548 SLocRemap &Remap = Mod->SLocRemap;
2549 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2550 // Rebuild the StoredDiagnostic.
2551 const StoredDiagnostic &SD = Diags[I];
2552 SourceLocation L = SD.getLocation();
2553 TranslateSLoc(L, Remap);
2554 FullSourceLoc Loc(L, SrcMgr);
2555
Chris Lattner5f9e2722011-07-23 10:55:15 +00002556 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002557 Ranges.reserve(SD.range_size());
2558 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2559 E = SD.range_end();
2560 I != E; ++I) {
2561 SourceLocation BL = I->getBegin();
2562 TranslateSLoc(BL, Remap);
2563 SourceLocation EL = I->getEnd();
2564 TranslateSLoc(EL, Remap);
2565 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2566 }
2567
Chris Lattner5f9e2722011-07-23 10:55:15 +00002568 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002569 FixIts.reserve(SD.fixit_size());
2570 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2571 E = SD.fixit_end();
2572 I != E; ++I) {
2573 FixIts.push_back(FixItHint());
2574 FixItHint &FH = FixIts.back();
2575 FH.CodeToInsert = I->CodeToInsert;
2576 SourceLocation BL = I->RemoveRange.getBegin();
2577 TranslateSLoc(BL, Remap);
2578 SourceLocation EL = I->RemoveRange.getEnd();
2579 TranslateSLoc(EL, Remap);
2580 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2581 I->RemoveRange.isTokenRange());
2582 }
2583
2584 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2585 SD.getMessage(), Loc, Ranges, FixIts));
2586 }
2587 Result.swap(Out);
2588}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002589
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002590static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2591 std::pair<unsigned, Decl *> R) {
2592 return L.first < R.first;
2593}
2594
2595void ASTUnit::addFileLevelDecl(Decl *D) {
2596 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002597
2598 // We only care about local declarations.
2599 if (D->isFromASTFile())
2600 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002601
2602 SourceManager &SM = *SourceMgr;
2603 SourceLocation Loc = D->getLocation();
2604 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2605 return;
2606
2607 // We only keep track of the file-level declarations of each file.
2608 if (!D->getLexicalDeclContext()->isFileContext())
2609 return;
2610
2611 SourceLocation FileLoc = SM.getFileLoc(Loc);
2612 assert(SM.isLocalSourceLocation(FileLoc));
2613 FileID FID;
2614 unsigned Offset;
2615 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2616 if (FID.isInvalid())
2617 return;
2618
2619 LocDeclsTy *&Decls = FileDecls[FID];
2620 if (!Decls)
2621 Decls = new LocDeclsTy();
2622
2623 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2624
2625 if (Decls->empty() || Decls->back().first <= Offset) {
2626 Decls->push_back(LocDecl);
2627 return;
2628 }
2629
2630 LocDeclsTy::iterator
2631 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2632
2633 Decls->insert(I, LocDecl);
2634}
2635
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002636void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2637 SmallVectorImpl<Decl *> &Decls) {
2638 if (File.isInvalid())
2639 return;
2640
2641 if (SourceMgr->isLoadedFileID(File)) {
2642 assert(Ctx->getExternalSource() && "No external source!");
2643 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2644 Decls);
2645 }
2646
2647 FileDeclsTy::iterator I = FileDecls.find(File);
2648 if (I == FileDecls.end())
2649 return;
2650
2651 LocDeclsTy &LocDecls = *I->second;
2652 if (LocDecls.empty())
2653 return;
2654
2655 LocDeclsTy::iterator
2656 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2657 std::make_pair(Offset, (Decl*)0), compLocDecl);
2658 if (BeginIt != LocDecls.begin())
2659 --BeginIt;
2660
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002661 // If we are pointing at a top-level decl inside an objc container, we need
2662 // to backtrack until we find it otherwise we will fail to report that the
2663 // region overlaps with an objc container.
2664 while (BeginIt != LocDecls.begin() &&
2665 BeginIt->second->isTopLevelDeclInObjCContainer())
2666 --BeginIt;
2667
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002668 LocDeclsTy::iterator
2669 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2670 std::make_pair(Offset+Length, (Decl*)0),
2671 compLocDecl);
2672 if (EndIt != LocDecls.end())
2673 ++EndIt;
2674
2675 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2676 Decls.push_back(DIt->second);
2677}
2678
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002679SourceLocation ASTUnit::getLocation(const FileEntry *File,
2680 unsigned Line, unsigned Col) const {
2681 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002682 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002683 return SM.getMacroArgExpandedLocation(Loc);
2684}
2685
2686SourceLocation ASTUnit::getLocation(const FileEntry *File,
2687 unsigned Offset) const {
2688 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002689 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002690 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2691}
2692
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002693/// \brief If \arg Loc is a loaded location from the preamble, returns
2694/// the corresponding local location of the main file, otherwise it returns
2695/// \arg Loc.
2696SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2697 FileID PreambleID;
2698 if (SourceMgr)
2699 PreambleID = SourceMgr->getPreambleFileID();
2700
2701 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2702 return Loc;
2703
2704 unsigned Offs;
2705 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2706 SourceLocation FileLoc
2707 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2708 return FileLoc.getLocWithOffset(Offs);
2709 }
2710
2711 return Loc;
2712}
2713
2714/// \brief If \arg Loc is a local location of the main file but inside the
2715/// preamble chunk, returns the corresponding loaded location from the
2716/// preamble, otherwise it returns \arg Loc.
2717SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2718 FileID PreambleID;
2719 if (SourceMgr)
2720 PreambleID = SourceMgr->getPreambleFileID();
2721
2722 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2723 return Loc;
2724
2725 unsigned Offs;
2726 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2727 Offs < Preamble.size()) {
2728 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2729 return FileLoc.getLocWithOffset(Offs);
2730 }
2731
2732 return Loc;
2733}
2734
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002735bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2736 FileID FID;
2737 if (SourceMgr)
2738 FID = SourceMgr->getPreambleFileID();
2739
2740 if (Loc.isInvalid() || FID.isInvalid())
2741 return false;
2742
2743 return SourceMgr->isInFileID(Loc, FID);
2744}
2745
2746bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2747 FileID FID;
2748 if (SourceMgr)
2749 FID = SourceMgr->getMainFileID();
2750
2751 if (Loc.isInvalid() || FID.isInvalid())
2752 return false;
2753
2754 return SourceMgr->isInFileID(Loc, FID);
2755}
2756
2757SourceLocation ASTUnit::getEndOfPreambleFileID() {
2758 FileID FID;
2759 if (SourceMgr)
2760 FID = SourceMgr->getPreambleFileID();
2761
2762 if (FID.isInvalid())
2763 return SourceLocation();
2764
2765 return SourceMgr->getLocForEndOfFile(FID);
2766}
2767
2768SourceLocation ASTUnit::getStartOfMainFileID() {
2769 FileID FID;
2770 if (SourceMgr)
2771 FID = SourceMgr->getMainFileID();
2772
2773 if (FID.isInvalid())
2774 return SourceLocation();
2775
2776 return SourceMgr->getLocForStartOfFile(FID);
2777}
2778
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002779void ASTUnit::PreambleData::countLines() const {
2780 NumLines = 0;
2781 if (empty())
2782 return;
2783
2784 for (std::vector<char>::const_iterator
2785 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2786 if (*I == '\n')
2787 ++NumLines;
2788 }
2789 if (Buffer.back() != '\n')
2790 ++NumLines;
2791}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002792
2793#ifndef NDEBUG
2794ASTUnit::ConcurrencyState::ConcurrencyState() {
2795 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2796}
2797
2798ASTUnit::ConcurrencyState::~ConcurrencyState() {
2799 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2800}
2801
2802void ASTUnit::ConcurrencyState::start() {
2803 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2804 assert(acquired && "Concurrent access to ASTUnit!");
2805}
2806
2807void ASTUnit::ConcurrencyState::finish() {
2808 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2809}
2810
2811#else // NDEBUG
2812
2813ASTUnit::ConcurrencyState::ConcurrencyState() {}
2814ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2815void ASTUnit::ConcurrencyState::start() {}
2816void ASTUnit::ConcurrencyState::finish() {}
2817
2818#endif