blob: 79559a3dcdbd73c775d1c546c6b834f4462b494e [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 Kyrtzidis98e95bf2012-09-15 01:10:20 +0000775 bool disableValid = false;
776 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
777 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000778 Reader.reset(new ASTReader(PP, Context,
779 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000780 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000781 /*DisableStatCache=*/false,
782 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000783
784 // Recover resources if we crash before exiting this method.
785 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
786 ReaderCleanup(Reader.get());
787
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000788 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000789 AST->ASTFileLangOpts, HeaderInfo,
790 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000791
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000792 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000793 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000794 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000796 case ASTReader::Failure:
797 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000798 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000799 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000800 }
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000802 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
803
Daniel Dunbard5b61262009-09-21 03:03:47 +0000804 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000805 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000807 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000808 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000809 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000810 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000811 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000812
813 // Unregister the cleanup for ASTReader. It will get cleaned up
814 // by the ASTUnit cleanup.
815 ReaderCleanup.unregister();
816
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 Context.setExternalSource(Source);
818
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000819 // Create an AST consumer, even though it isn't used.
820 AST->Consumer.reset(new ASTConsumer);
821
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000822 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000823 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
824 AST->TheSema->Initialize();
825 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000826 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000827
Mike Stump1eb44332009-09-09 15:08:12 +0000828 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000829}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000830
831namespace {
832
Douglas Gregor9b7db622011-02-16 18:16:54 +0000833/// \brief Preprocessor callback class that updates a hash value with the names
834/// of all macros that have been defined by the translation unit.
835class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
836 unsigned &Hash;
837
838public:
839 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
840
841 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
842 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
843 }
844};
845
846/// \brief Add the given declaration to the hash of all top-level entities.
847void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
848 if (!D)
849 return;
850
851 DeclContext *DC = D->getDeclContext();
852 if (!DC)
853 return;
854
855 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
856 return;
857
858 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
859 if (ND->getIdentifier())
860 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
861 else if (DeclarationName Name = ND->getDeclName()) {
862 std::string NameStr = Name.getAsString();
863 Hash = llvm::HashString(NameStr, Hash);
864 }
865 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000866 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000867}
868
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000869class TopLevelDeclTrackerConsumer : public ASTConsumer {
870 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000871 unsigned &Hash;
872
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000873public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000874 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
875 : Unit(_Unit), Hash(Hash) {
876 Hash = 0;
877 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000878
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000879 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000880 if (!D)
881 return;
882
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000883 // FIXME: Currently ObjC method declarations are incorrectly being
884 // reported as top-level declarations, even though their DeclContext
885 // is the containing ObjC @interface/@implementation. This is a
886 // fundamental problem in the parser right now.
887 if (isa<ObjCMethodDecl>(D))
888 return;
889
890 AddTopLevelDeclarationToHash(D, Hash);
891 Unit.addTopLevelDecl(D);
892
893 handleFileLevelDecl(D);
894 }
895
896 void handleFileLevelDecl(Decl *D) {
897 Unit.addFileLevelDecl(D);
898 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
899 for (NamespaceDecl::decl_iterator
900 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
901 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000902 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000903 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000904
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000905 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000906 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
907 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000908 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000909 }
910
Sebastian Redl27372b42010-08-11 18:52:41 +0000911 // We're not interested in "interesting" decls.
912 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000913
914 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
915 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
916 handleTopLevelDecl(*it);
917 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000918};
919
920class TopLevelDeclTrackerAction : public ASTFrontendAction {
921public:
922 ASTUnit &Unit;
923
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000924 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000925 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000926 CI.getPreprocessor().addPPCallbacks(
927 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
928 return new TopLevelDeclTrackerConsumer(Unit,
929 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000930 }
931
932public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000933 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
934
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000935 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000936 virtual TranslationUnitKind getTranslationUnitKind() {
937 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000938 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000939};
940
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000941class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000942 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000943 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000944 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000945
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000946public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000947 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000948 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000949 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000950 Hash(Unit.getCurrentTopLevelHashValue()) {
951 Hash = 0;
952 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000953
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000954 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000955 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
956 Decl *D = *it;
957 // FIXME: Currently ObjC method declarations are incorrectly being
958 // reported as top-level declarations, even though their DeclContext
959 // is the containing ObjC @interface/@implementation. This is a
960 // fundamental problem in the parser right now.
961 if (isa<ObjCMethodDecl>(D))
962 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000963 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000964 TopLevelDecls.push_back(D);
965 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000966 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000967 }
968
969 virtual void HandleTranslationUnit(ASTContext &Ctx) {
970 PCHGenerator::HandleTranslationUnit(Ctx);
971 if (!Unit.getDiagnostics().hasErrorOccurred()) {
972 // Translate the top-level declarations we captured during
973 // parsing into declaration IDs in the precompiled
974 // preamble. This will allow us to deserialize those top-level
975 // declarations when requested.
976 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
977 Unit.addTopLevelDeclFromPreamble(
978 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000979 }
980 }
981};
982
983class PrecompilePreambleAction : public ASTFrontendAction {
984 ASTUnit &Unit;
985
986public:
987 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
988
989 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000990 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000991 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000992 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000993 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000994 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
995 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000996 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000997 return 0;
998
Douglas Gregor832d6202011-07-22 16:35:34 +0000999 if (!CI.getFrontendOpts().RelocatablePCH)
1000 Sysroot.clear();
1001
Douglas Gregor9b7db622011-02-16 18:16:54 +00001002 CI.getPreprocessor().addPPCallbacks(
1003 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001004 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1005 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001006 }
1007
1008 virtual bool hasCodeCompletionSupport() const { return false; }
1009 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001010 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001011};
1012
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001013}
1014
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001015static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1016 StoredDiagnostics) {
1017 // Get rid of stored diagnostics except the ones from the driver which do not
1018 // have a source location.
1019 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1020 if (StoredDiagnostics[I].getLocation().isValid()) {
1021 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1022 --I;
1023 }
1024 }
1025}
1026
1027static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1028 StoredDiagnostics,
1029 SourceManager &SM) {
1030 // The stored diagnostic has the old source manager in it; update
1031 // the locations to refer into the new source manager. Since we've
1032 // been careful to make sure that the source manager's state
1033 // before and after are identical, so that we can reuse the source
1034 // location itself.
1035 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1036 if (StoredDiagnostics[I].getLocation().isValid()) {
1037 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1038 StoredDiagnostics[I].setLocation(Loc);
1039 }
1040 }
1041}
1042
Douglas Gregorabc563f2010-07-19 21:46:24 +00001043/// Parse the source file into a translation unit using the given compiler
1044/// invocation, replacing the current translation unit.
1045///
1046/// \returns True if a failure occurred that causes the ASTUnit not to
1047/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001048bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001049 delete SavedMainFileBuffer;
1050 SavedMainFileBuffer = 0;
1051
Ted Kremenek4f327862011-03-21 18:40:17 +00001052 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001053 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001054 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001055 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001056
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001057 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001058 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001059
1060 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001061 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1062 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001064 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001065 CCInvocation(new CompilerInvocation(*Invocation));
1066
1067 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001068 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001069
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001070 // Set up diagnostics, capturing any diagnostics that would
1071 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001072 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001073
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001074 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001075 Clang->getTargetOpts().Features = TargetFeatures;
1076 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001077 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001078 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001079 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001080 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001081 }
1082
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001083 // Inform the target of the language options.
1084 //
1085 // FIXME: We shouldn't need to do this, the target should be immutable once
1086 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001087 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088
Ted Kremenek03201fb2011-03-21 18:40:07 +00001089 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001090 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001091 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001093 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001094 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001095
Douglas Gregorabc563f2010-07-19 21:46:24 +00001096 // Configure the various subsystems.
1097 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001098 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001100 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001101 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1102 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001103 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001104 Ctx = 0;
1105 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001106 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001107
1108 // Clear out old caches and data.
1109 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001110 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001111 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001112
Douglas Gregorf128fed2010-08-20 00:02:33 +00001113 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001114 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001115 TopLevelDeclsInPreamble.clear();
1116 }
1117
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001118 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001119 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001121 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001122 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001123
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001124 // If the main file has been overridden due to the use of a preamble,
1125 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001126 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001127 if (OverrideMainBuffer) {
1128 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1129 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1130 PreprocessorOpts.PrecompiledPreambleBytes.second
1131 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001132 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001133 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001134
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001135 // The stored diagnostic has the old source manager in it; update
1136 // the locations to refer into the new source manager. Since we've
1137 // been careful to make sure that the source manager's state
1138 // before and after are identical, so that we can reuse the source
1139 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001140 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001141
1142 // Keep track of the override buffer;
1143 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001144 }
1145
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001146 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001147 new TopLevelDeclTrackerAction(*this));
1148
1149 // Recover resources if we crash before exiting this method.
1150 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1151 ActCleanup(Act.get());
1152
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001153 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001154 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001155
1156 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001157 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001158 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1159 getSourceManager(), PreambleDiagnostics,
1160 StoredDiagnostics);
1161 }
1162
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001163 if (!Act->Execute())
1164 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001165
1166 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001167
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001168 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001169
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001170 FailedParseDiagnostics.clear();
1171
Douglas Gregorabc563f2010-07-19 21:46:24 +00001172 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001173
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001174error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001175 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001176 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001177 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001178 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001179 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001180
1181 // Keep the ownership of the data in the ASTUnit because the client may
1182 // want to see the diagnostics.
1183 transferASTDataFromCompilerInstance(*Clang);
1184 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001185 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001186 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001187 return true;
1188}
1189
Douglas Gregor44c181a2010-07-23 00:33:23 +00001190/// \brief Simple function to retrieve a path for a preamble precompiled header.
1191static std::string GetPreamblePCHPath() {
1192 // FIXME: This is lame; sys::Path should provide this function (in particular,
1193 // it should know how to find the temporary files dir).
1194 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001195 // FIXME: This is a hack so that we can override the preamble file during
1196 // crash-recovery testing, which is the only case where the preamble files
1197 // are not necessarily cleaned up.
1198 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1199 if (TmpFile)
1200 return TmpFile;
1201
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202 std::string Error;
1203 const char *TmpDir = ::getenv("TMPDIR");
1204 if (!TmpDir)
1205 TmpDir = ::getenv("TEMP");
1206 if (!TmpDir)
1207 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001208#ifdef LLVM_ON_WIN32
1209 if (!TmpDir)
1210 TmpDir = ::getenv("USERPROFILE");
1211#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001212 if (!TmpDir)
1213 TmpDir = "/tmp";
1214 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001215 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001217 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001218 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 return std::string();
1220
Douglas Gregor44c181a2010-07-23 00:33:23 +00001221 return P.str();
1222}
1223
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001224/// \brief Compute the preamble for the main file, providing the source buffer
1225/// that corresponds to the main file along with a pair (bytes, start-of-line)
1226/// that describes the preamble.
1227std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001228ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1229 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001230 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001231 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001232 CreatedBuffer = false;
1233
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234 // Try to determine if the main file has been remapped, either from the
1235 // command line (to another file) or directly through the compiler invocation
1236 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001237 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001238 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001239 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1240 // Check whether there is a file-file remapping of the main file
1241 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001242 M = PreprocessorOpts.remapped_file_begin(),
1243 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001244 M != E;
1245 ++M) {
1246 llvm::sys::PathWithStatus MPath(M->first);
1247 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1248 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1249 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001250 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 CreatedBuffer = false;
1253 }
1254
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001255 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001257 return std::make_pair((llvm::MemoryBuffer*)0,
1258 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001260 }
1261 }
1262 }
1263
1264 // Check whether there is a file-buffer remapping. It supercedes the
1265 // file-file remapping.
1266 for (PreprocessorOptions::remapped_file_buffer_iterator
1267 M = PreprocessorOpts.remapped_file_buffer_begin(),
1268 E = PreprocessorOpts.remapped_file_buffer_end();
1269 M != E;
1270 ++M) {
1271 llvm::sys::PathWithStatus MPath(M->first);
1272 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1273 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1274 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001275 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001276 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 CreatedBuffer = false;
1278 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001279
Douglas Gregor175c4a92010-07-23 23:58:40 +00001280 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 }
1282 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001284 }
1285
1286 // If the main source file was not remapped, load it now.
1287 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001288 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001289 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001290 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001291
1292 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293 }
1294
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001295 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001296 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001297 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001298}
1299
Douglas Gregor754f3492010-07-24 00:38:13 +00001300static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001301 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001302 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001303 llvm::MemoryBuffer *Result
1304 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1305 memcpy(const_cast<char*>(Result->getBufferStart()),
1306 Old->getBufferStart(), Old->getBufferSize());
1307 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001308 ' ', NewSize - Old->getBufferSize() - 1);
1309 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001310
Douglas Gregor754f3492010-07-24 00:38:13 +00001311 return Result;
1312}
1313
Douglas Gregor175c4a92010-07-23 23:58:40 +00001314/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1315/// the source file.
1316///
1317/// This routine will compute the preamble of the main source file. If a
1318/// non-trivial preamble is found, it will precompile that preamble into a
1319/// precompiled header so that the precompiled preamble can be used to reduce
1320/// reparsing time. If a precompiled preamble has already been constructed,
1321/// this routine will determine if it is still valid and, if so, avoid
1322/// rebuilding the precompiled preamble.
1323///
Douglas Gregordf95a132010-08-09 20:45:32 +00001324/// \param AllowRebuild When true (the default), this routine is
1325/// allowed to rebuild the precompiled preamble if it is found to be
1326/// out-of-date.
1327///
1328/// \param MaxLines When non-zero, the maximum number of lines that
1329/// can occur within the preamble.
1330///
Douglas Gregor754f3492010-07-24 00:38:13 +00001331/// \returns If the precompiled preamble can be used, returns a newly-allocated
1332/// buffer that should be used in place of the main file when doing so.
1333/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001334llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001335 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001336 bool AllowRebuild,
1337 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001338
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001339 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001340 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1341 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001342 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001343 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001344
1345 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001346 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001347 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001348
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001349 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001350 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001351 if (CreatedPreambleBuffer)
1352 OwnedPreambleBuffer.reset(NewPreamble.first);
1353
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001354 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001355 // We couldn't find a preamble in the main source. Clear out the current
1356 // preamble, if we have one. It's obviously no good any more.
1357 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001358 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001359
1360 // The next time we actually see a preamble, precompile it.
1361 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001362 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001363 }
1364
1365 if (!Preamble.empty()) {
1366 // We've previously computed a preamble. Check whether we have the same
1367 // preamble now that we did before, and that there's enough space in
1368 // the main-file buffer within the precompiled preamble to fit the
1369 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001370 if (Preamble.size() == NewPreamble.second.first &&
1371 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001372 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001373 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001374 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001375 // The preamble has not changed. We may be able to re-use the precompiled
1376 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001377
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001378 // Check that none of the files used by the preamble have changed.
1379 bool AnyFileChanged = false;
1380
1381 // First, make a record of those files that have been overridden via
1382 // remapping or unsaved_files.
1383 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1384 for (PreprocessorOptions::remapped_file_iterator
1385 R = PreprocessorOpts.remapped_file_begin(),
1386 REnd = PreprocessorOpts.remapped_file_end();
1387 !AnyFileChanged && R != REnd;
1388 ++R) {
1389 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001390 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001391 // If we can't stat the file we're remapping to, assume that something
1392 // horrible happened.
1393 AnyFileChanged = true;
1394 break;
1395 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001396
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001397 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1398 StatBuf.st_mtime);
1399 }
1400 for (PreprocessorOptions::remapped_file_buffer_iterator
1401 R = PreprocessorOpts.remapped_file_buffer_begin(),
1402 REnd = PreprocessorOpts.remapped_file_buffer_end();
1403 !AnyFileChanged && R != REnd;
1404 ++R) {
1405 // FIXME: Should we actually compare the contents of file->buffer
1406 // remappings?
1407 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1408 0);
1409 }
1410
1411 // Check whether anything has changed.
1412 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1413 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1414 !AnyFileChanged && F != FEnd;
1415 ++F) {
1416 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1417 = OverriddenFiles.find(F->first());
1418 if (Overridden != OverriddenFiles.end()) {
1419 // This file was remapped; check whether the newly-mapped file
1420 // matches up with the previous mapping.
1421 if (Overridden->second != F->second)
1422 AnyFileChanged = true;
1423 continue;
1424 }
1425
1426 // The file was not remapped; check whether it has changed on disk.
1427 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001428 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001429 // If we can't stat the file, assume that something horrible happened.
1430 AnyFileChanged = true;
1431 } else if (StatBuf.st_size != F->second.first ||
1432 StatBuf.st_mtime != F->second.second)
1433 AnyFileChanged = true;
1434 }
1435
1436 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001437 // Okay! We can re-use the precompiled preamble.
1438
1439 // Set the state of the diagnostic object to mimic its state
1440 // after parsing the preamble.
1441 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001442 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001443 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001444 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001445
1446 // Create a version of the main file buffer that is padded to
1447 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001448 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001449 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001450 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001451 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001452 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001453
1454 // If we aren't allowed to rebuild the precompiled preamble, just
1455 // return now.
1456 if (!AllowRebuild)
1457 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001458
Douglas Gregor175c4a92010-07-23 23:58:40 +00001459 // We can't reuse the previously-computed preamble. Build a new one.
1460 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001461 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001462 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001463 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001464 } else if (!AllowRebuild) {
1465 // We aren't allowed to rebuild the precompiled preamble; just
1466 // return now.
1467 return 0;
1468 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001469
1470 // If the preamble rebuild counter > 1, it's because we previously
1471 // failed to build a preamble and we're not yet ready to try
1472 // again. Decrement the counter and return a failure.
1473 if (PreambleRebuildCounter > 1) {
1474 --PreambleRebuildCounter;
1475 return 0;
1476 }
1477
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001478 // Create a temporary file for the precompiled preamble. In rare
1479 // circumstances, this can fail.
1480 std::string PreamblePCHPath = GetPreamblePCHPath();
1481 if (PreamblePCHPath.empty()) {
1482 // Try again next time.
1483 PreambleRebuildCounter = 1;
1484 return 0;
1485 }
1486
Douglas Gregor175c4a92010-07-23 23:58:40 +00001487 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001488 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001489 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001490
1491 // Create a new buffer that stores the preamble. The buffer also contains
1492 // extra space for the original contents of the file (which will be present
1493 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001494 // grows.
1495 PreambleReservedSize = NewPreamble.first->getBufferSize();
1496 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001497 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001498 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001499 PreambleReservedSize *= 2;
1500
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001501 // Save the preamble text for later; we'll need to compare against it for
1502 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001503 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001504 Preamble.assign(FileMgr->getFile(MainFilename),
1505 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001506 NewPreamble.first->getBufferStart()
1507 + NewPreamble.second.first);
1508 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1509
Douglas Gregor671947b2010-08-19 01:33:06 +00001510 delete PreambleBuffer;
1511 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001512 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001513 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001514 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001515 NewPreamble.first->getBufferStart(), Preamble.size());
1516 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001517 ' ', PreambleReservedSize - Preamble.size() - 1);
1518 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001519
1520 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001521 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1523
1524 // Tell the compiler invocation to generate a temporary precompiled header.
1525 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001527 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001528 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1529 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001530
1531 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001532 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001533
1534 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001535 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1536 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001537
Douglas Gregor01b6e312011-07-01 18:22:13 +00001538 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001539 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001541 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001542 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001543
1544 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001545 Clang->getTargetOpts().Features = TargetFeatures;
1546 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1547 Clang->getTargetOpts()));
1548 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001549 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1550 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001551 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001552 PreprocessorOpts.eraseRemappedFile(
1553 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001554 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555 }
1556
1557 // Inform the target of the language options.
1558 //
1559 // FIXME: We shouldn't need to do this, the target should be immutable once
1560 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001561 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001562
Ted Kremenek03201fb2011-03-21 18:40:07 +00001563 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001565 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001567 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568 "IR inputs not support here!");
1569
1570 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001571 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001572 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001573 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001574 TopLevelDecls.clear();
1575 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001576
1577 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001578 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579
1580 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001581 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001582 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001583
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001584 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001585 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001586 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001587 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1588 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001589 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001590 PreprocessorOpts.eraseRemappedFile(
1591 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001592 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001593 }
1594
1595 Act->Execute();
1596 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001597
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001598 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001599 // There were errors parsing the preamble, so no precompiled header was
1600 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001601 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001602 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1603 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001604 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001605 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001606 PreprocessorOpts.eraseRemappedFile(
1607 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001608 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001609 }
1610
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001611 // Transfer any diagnostics generated when parsing the preamble into the set
1612 // of preamble diagnostics.
1613 PreambleDiagnostics.clear();
1614 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001615 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001616 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001617
Douglas Gregor175c4a92010-07-23 23:58:40 +00001618 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001619 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001620 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001621
1622 // Keep track of all of the files that the source manager knows about,
1623 // so we can verify whether they have changed or not.
1624 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001625 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001626 const llvm::MemoryBuffer *MainFileBuffer
1627 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1628 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1629 FEnd = SourceMgr.fileinfo_end();
1630 F != FEnd;
1631 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001632 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001633 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1634 continue;
1635
1636 FilesInPreamble[File->getName()]
1637 = std::make_pair(F->second->getSize(), File->getModificationTime());
1638 }
1639
Douglas Gregoreababfb2010-08-04 05:53:38 +00001640 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001641 PreprocessorOpts.eraseRemappedFile(
1642 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001643
1644 // If the hash of top-level entities differs from the hash of the top-level
1645 // entities the last time we rebuilt the preamble, clear out the completion
1646 // cache.
1647 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1648 CompletionCacheTopLevelHashValue = 0;
1649 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1650 }
1651
Douglas Gregor754f3492010-07-24 00:38:13 +00001652 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001653 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001654 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001655}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001656
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001657void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1658 std::vector<Decl *> Resolved;
1659 Resolved.reserve(TopLevelDeclsInPreamble.size());
1660 ExternalASTSource &Source = *getASTContext().getExternalSource();
1661 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1662 // Resolve the declaration ID to an actual declaration, possibly
1663 // deserializing the declaration in the process.
1664 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1665 if (D)
1666 Resolved.push_back(D);
1667 }
1668 TopLevelDeclsInPreamble.clear();
1669 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1670}
1671
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001672void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1673 // Steal the created target, context, and preprocessor.
1674 TheSema.reset(CI.takeSema());
1675 Consumer.reset(CI.takeASTConsumer());
1676 Ctx = &CI.getASTContext();
1677 PP = &CI.getPreprocessor();
1678 CI.setSourceManager(0);
1679 CI.setFileManager(0);
1680 Target = &CI.getTarget();
1681 Reader = CI.getModuleManager();
1682}
1683
Chris Lattner5f9e2722011-07-23 10:55:15 +00001684StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001685 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001686}
1687
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001688ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001689 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001690 bool CaptureDiagnostics,
1691 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001692 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001693 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001694 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001695 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001696 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001697 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001698 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001699 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1700 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1701 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001702
1703 return AST.take();
1704}
1705
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001706ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001707 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001708 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001709 ASTUnit *Unit,
1710 bool Persistent,
1711 StringRef ResourceFilesPath,
1712 bool OnlyLocalDecls,
1713 bool CaptureDiagnostics,
1714 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001715 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001716 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001717 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001718 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001719 assert(CI && "A CompilerInvocation is required");
1720
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001721 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001722 ASTUnit *AST = Unit;
1723 if (!AST) {
1724 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001725 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001726 AST = OwnAST.get();
1727 }
1728
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001729 if (!ResourceFilesPath.empty()) {
1730 // Override the resources path.
1731 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1732 }
1733 AST->OnlyLocalDecls = OnlyLocalDecls;
1734 AST->CaptureDiagnostics = CaptureDiagnostics;
1735 if (PrecompilePreamble)
1736 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001737 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001738 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001739 AST->IncludeBriefCommentsInCodeCompletion
1740 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001741
1742 // Recover resources if we crash before exiting this method.
1743 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001744 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001745 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1746 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001747 DiagCleanup(Diags.getPtr());
1748
1749 // We'll manage file buffers ourselves.
1750 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1751 CI->getFrontendOpts().DisableFree = false;
1752 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1753
1754 // Save the target features.
1755 AST->TargetFeatures = CI->getTargetOpts().Features;
1756
1757 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001758 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001759
1760 // Recover resources if we crash before exiting this method.
1761 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1762 CICleanup(Clang.get());
1763
1764 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001765 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001766
1767 // Set up diagnostics, capturing any diagnostics that would
1768 // otherwise be dropped.
1769 Clang->setDiagnostics(&AST->getDiagnostics());
1770
1771 // Create the target instance.
1772 Clang->getTargetOpts().Features = AST->TargetFeatures;
1773 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1774 Clang->getTargetOpts()));
1775 if (!Clang->hasTarget())
1776 return 0;
1777
1778 // Inform the target of the language options.
1779 //
1780 // FIXME: We shouldn't need to do this, the target should be immutable once
1781 // created. This complexity should be lifted elsewhere.
1782 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1783
1784 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1785 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001786 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001787 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001788 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 "IR inputs not supported here!");
1790
1791 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001792 AST->TheSema.reset();
1793 AST->Ctx = 0;
1794 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001795 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001796
1797 // Create a file manager object to provide access to and cache the filesystem.
1798 Clang->setFileManager(&AST->getFileManager());
1799
1800 // Create the source manager.
1801 Clang->setSourceManager(&AST->getSourceManager());
1802
1803 ASTFrontendAction *Act = Action;
1804
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001805 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001806 if (!Act) {
1807 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1808 Act = TrackerAct.get();
1809 }
1810
1811 // Recover resources if we crash before exiting this method.
1812 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1813 ActCleanup(TrackerAct.get());
1814
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001815 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1816 AST->transferASTDataFromCompilerInstance(*Clang);
1817 if (OwnAST && ErrAST)
1818 ErrAST->swap(OwnAST);
1819
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001820 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001821 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001822
1823 if (Persistent && !TrackerAct) {
1824 Clang->getPreprocessor().addPPCallbacks(
1825 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1826 std::vector<ASTConsumer*> Consumers;
1827 if (Clang->hasASTConsumer())
1828 Consumers.push_back(Clang->takeASTConsumer());
1829 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1830 AST->getCurrentTopLevelHashValue()));
1831 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1832 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001833 if (!Act->Execute()) {
1834 AST->transferASTDataFromCompilerInstance(*Clang);
1835 if (OwnAST && ErrAST)
1836 ErrAST->swap(OwnAST);
1837
1838 return 0;
1839 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001840
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001841 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001842 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001843
1844 Act->EndSourceFile();
1845
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001846 if (OwnAST)
1847 return OwnAST.take();
1848 else
1849 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001850}
1851
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001852bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1853 if (!Invocation)
1854 return true;
1855
1856 // We'll manage file buffers ourselves.
1857 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1858 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001859 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001860
Douglas Gregor1aa27302011-01-27 18:02:58 +00001861 // Save the target features.
1862 TargetFeatures = Invocation->getTargetOpts().Features;
1863
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001864 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001865 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001866 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001867 OverrideMainBuffer
1868 = getMainBufferWithPrecompiledPreamble(*Invocation);
1869 }
1870
Douglas Gregor213f18b2010-10-28 15:44:59 +00001871 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001872 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001873
Ted Kremenek25a11e12011-03-22 01:15:24 +00001874 // Recover resources if we crash before exiting this method.
1875 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1876 MemBufferCleanup(OverrideMainBuffer);
1877
Douglas Gregor213f18b2010-10-28 15:44:59 +00001878 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001879}
1880
Douglas Gregorabc563f2010-07-19 21:46:24 +00001881ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001882 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001883 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001884 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001885 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001886 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001887 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001888 bool IncludeBriefCommentsInCodeCompletion,
1889 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001890 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001891 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001892 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001893 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001895 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001896 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001897 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001898 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001899 AST->IncludeBriefCommentsInCodeCompletion
1900 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001901 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001902 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001903
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001904 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001905 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1906 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001907 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1908 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001909 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001910
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001912}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001913
1914ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1915 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001916 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001917 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001918 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001919 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001920 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001921 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001922 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001923 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001924 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001925 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001926 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001927 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001928 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001929 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001930 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001931 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001932 // No diagnostics engine was provided, so create our own diagnostics object
1933 // with the default options.
1934 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001935 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1936 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001937 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001938
Chris Lattner5f9e2722011-07-23 10:55:15 +00001939 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001940
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001941 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001942
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001943 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001944
Douglas Gregore47be3e2010-11-11 00:39:14 +00001945 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001946 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001947
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001948 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001949 llvm::makeArrayRef(ArgBegin, ArgEnd),
1950 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001951 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001952 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001953 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001954
Douglas Gregor4db64a42010-01-23 00:14:00 +00001955 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001956 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1957 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1958 if (const llvm::MemoryBuffer *
1959 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1960 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1961 } else {
1962 const char *fname = fileOrBuf.get<const char *>();
1963 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1964 }
1965 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001966 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1967 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1968 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001969
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001970 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001971 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001972
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001973 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1974
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001975 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001976 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001977 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001978 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001979 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001980 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001981 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001982 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001983 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001984 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001985 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001986 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001987 AST->IncludeBriefCommentsInCodeCompletion
1988 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001989 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001990 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001991 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001992 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001993 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001994
1995 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001996 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1997 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001998
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001999 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2000 // Some error occurred, if caller wants to examine diagnostics, pass it the
2001 // ASTUnit.
2002 if (ErrAST) {
2003 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2004 ErrAST->swap(AST);
2005 }
2006 return 0;
2007 }
2008
2009 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002010}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002011
2012bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002013 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002014 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002015
2016 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002017
Douglas Gregor213f18b2010-10-28 15:44:59 +00002018 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002019 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002020
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002021 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002022 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002023 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002024 for (PreprocessorOptions::remapped_file_buffer_iterator
2025 R = PPOpts.remapped_file_buffer_begin(),
2026 REnd = PPOpts.remapped_file_buffer_end();
2027 R != REnd;
2028 ++R) {
2029 delete R->second;
2030 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002031 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002032 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2033 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2034 if (const llvm::MemoryBuffer *
2035 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2036 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2037 memBuf);
2038 } else {
2039 const char *fname = fileOrBuf.get<const char *>();
2040 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2041 fname);
2042 }
2043 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002044
Douglas Gregoreababfb2010-08-04 05:53:38 +00002045 // If we have a preamble file lying around, or if we might try to
2046 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002047 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002048 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002049 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002050
Douglas Gregorabc563f2010-07-19 21:46:24 +00002051 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002052 getDiagnostics().Reset();
2053 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002054 if (OverrideMainBuffer)
2055 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002056
Douglas Gregor175c4a92010-07-23 23:58:40 +00002057 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002058 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002059
2060 // If we're caching global code-completion results, and the top-level
2061 // declarations have changed, clear out the code-completion cache.
2062 if (!Result && ShouldCacheCodeCompletionResults &&
2063 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2064 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002065
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002066 // We now need to clear out the completion info related to this translation
2067 // unit; it'll be recreated if necessary.
2068 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002069
Douglas Gregor175c4a92010-07-23 23:58:40 +00002070 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002071}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002072
Douglas Gregor87c08a52010-08-13 22:48:40 +00002073//----------------------------------------------------------------------------//
2074// Code completion
2075//----------------------------------------------------------------------------//
2076
2077namespace {
2078 /// \brief Code completion consumer that combines the cached code-completion
2079 /// results from an ASTUnit with the code-completion results provided to it,
2080 /// then passes the result on to
2081 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002082 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002083 ASTUnit &AST;
2084 CodeCompleteConsumer &Next;
2085
2086 public:
2087 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002088 const CodeCompleteOptions &CodeCompleteOpts)
2089 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2090 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002091 {
2092 // Compute the set of contexts in which we will look when we don't have
2093 // any information about the specific context.
2094 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002095 = (1LL << CodeCompletionContext::CCC_TopLevel)
2096 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2097 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2098 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2099 | (1LL << CodeCompletionContext::CCC_Statement)
2100 | (1LL << CodeCompletionContext::CCC_Expression)
2101 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2102 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2103 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2104 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2105 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2106 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2107 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002108
David Blaikie4e4d0842012-03-11 07:00:24 +00002109 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002110 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2111 | (1LL << CodeCompletionContext::CCC_UnionTag)
2112 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002113 }
2114
2115 virtual void ProcessCodeCompleteResults(Sema &S,
2116 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002117 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002118 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002119
2120 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2121 OverloadCandidate *Candidates,
2122 unsigned NumCandidates) {
2123 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2124 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002125
Douglas Gregordae68752011-02-01 22:57:45 +00002126 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002127 return Next.getAllocator();
2128 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002129
2130 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2131 return Next.getCodeCompletionTUInfo();
2132 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002133 };
2134}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002135
Douglas Gregor5f808c22010-08-16 21:18:39 +00002136/// \brief Helper function that computes which global names are hidden by the
2137/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002138static void CalculateHiddenNames(const CodeCompletionContext &Context,
2139 CodeCompletionResult *Results,
2140 unsigned NumResults,
2141 ASTContext &Ctx,
2142 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002143 bool OnlyTagNames = false;
2144 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002145 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002146 case CodeCompletionContext::CCC_TopLevel:
2147 case CodeCompletionContext::CCC_ObjCInterface:
2148 case CodeCompletionContext::CCC_ObjCImplementation:
2149 case CodeCompletionContext::CCC_ObjCIvarList:
2150 case CodeCompletionContext::CCC_ClassStructUnion:
2151 case CodeCompletionContext::CCC_Statement:
2152 case CodeCompletionContext::CCC_Expression:
2153 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002154 case CodeCompletionContext::CCC_DotMemberAccess:
2155 case CodeCompletionContext::CCC_ArrowMemberAccess:
2156 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002157 case CodeCompletionContext::CCC_Namespace:
2158 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002159 case CodeCompletionContext::CCC_Name:
2160 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002161 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002162 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002163 break;
2164
2165 case CodeCompletionContext::CCC_EnumTag:
2166 case CodeCompletionContext::CCC_UnionTag:
2167 case CodeCompletionContext::CCC_ClassOrStructTag:
2168 OnlyTagNames = true;
2169 break;
2170
2171 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002172 case CodeCompletionContext::CCC_MacroName:
2173 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002174 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002175 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002176 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002177 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002178 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002179 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002180 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002181 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2182 case CodeCompletionContext::CCC_ObjCClassMessage:
2183 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002184 // We're looking for nothing, or we're looking for names that cannot
2185 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002186 return;
2187 }
2188
John McCall0a2c5e22010-08-25 06:19:51 +00002189 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002190 for (unsigned I = 0; I != NumResults; ++I) {
2191 if (Results[I].Kind != Result::RK_Declaration)
2192 continue;
2193
2194 unsigned IDNS
2195 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2196
2197 bool Hiding = false;
2198 if (OnlyTagNames)
2199 Hiding = (IDNS & Decl::IDNS_Tag);
2200 else {
2201 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002202 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2203 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002204 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002205 HiddenIDNS |= Decl::IDNS_Tag;
2206 Hiding = (IDNS & HiddenIDNS);
2207 }
2208
2209 if (!Hiding)
2210 continue;
2211
2212 DeclarationName Name = Results[I].Declaration->getDeclName();
2213 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2214 HiddenNames.insert(Identifier->getName());
2215 else
2216 HiddenNames.insert(Name.getAsString());
2217 }
2218}
2219
2220
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002221void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2222 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002223 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002224 unsigned NumResults) {
2225 // Merge the results we were given with the results we cached.
2226 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002227 uint64_t InContexts =
2228 Context.getKind() == CodeCompletionContext::CCC_Recovery
2229 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002230 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002231 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002232 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002233 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002234 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002235 C = AST.cached_completion_begin(),
2236 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002237 C != CEnd; ++C) {
2238 // If the context we are in matches any of the contexts we are
2239 // interested in, we'll add this result.
2240 if ((C->ShowInContexts & InContexts) == 0)
2241 continue;
2242
2243 // If we haven't added any results previously, do so now.
2244 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002245 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2246 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002247 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2248 AddedResult = true;
2249 }
2250
Douglas Gregor5f808c22010-08-16 21:18:39 +00002251 // Determine whether this global completion result is hidden by a local
2252 // completion result. If so, skip it.
2253 if (C->Kind != CXCursor_MacroDefinition &&
2254 HiddenNames.count(C->Completion->getTypedText()))
2255 continue;
2256
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002257 // Adjust priority based on similar type classes.
2258 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002259 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002260 if (!Context.getPreferredType().isNull()) {
2261 if (C->Kind == CXCursor_MacroDefinition) {
2262 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002263 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002264 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002265 } else if (C->Type) {
2266 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002267 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002268 Context.getPreferredType().getUnqualifiedType());
2269 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2270 if (ExpectedSTC == C->TypeClass) {
2271 // We know this type is similar; check for an exact match.
2272 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002273 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002274 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002275 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002276 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2277 Priority /= CCF_ExactTypeMatch;
2278 else
2279 Priority /= CCF_SimilarTypeMatch;
2280 }
2281 }
2282 }
2283
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002284 // Adjust the completion string, if required.
2285 if (C->Kind == CXCursor_MacroDefinition &&
2286 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2287 // Create a new code-completion string that just contains the
2288 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002289 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2290 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002291 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002292 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002293 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002294 }
2295
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002296 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002297 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002298 }
2299
2300 // If we did not add any cached completion results, just forward the
2301 // results we were given to the next consumer.
2302 if (!AddedResult) {
2303 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2304 return;
2305 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002306
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002307 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2308 AllResults.size());
2309}
2310
2311
2312
Chris Lattner5f9e2722011-07-23 10:55:15 +00002313void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002314 RemappedFile *RemappedFiles,
2315 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002316 bool IncludeMacros,
2317 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002318 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002319 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002320 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002321 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002322 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2323 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002324 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002325 return;
2326
Douglas Gregor213f18b2010-10-28 15:44:59 +00002327 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002328 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002329 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002330
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002331 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002332 CCInvocation(new CompilerInvocation(*Invocation));
2333
2334 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002335 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002336 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002337
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002338 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2339 CachedCompletionResults.empty();
2340 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2341 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2342 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2343
2344 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2345
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 FrontendOpts.CodeCompletionAt.FileName = File;
2347 FrontendOpts.CodeCompletionAt.Line = Line;
2348 FrontendOpts.CodeCompletionAt.Column = Column;
2349
2350 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002351 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002352
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002353 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002354
2355 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002356 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2357 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002358
Ted Kremenek4f327862011-03-21 18:40:17 +00002359 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002360 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002361
2362 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002363 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002364 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002365 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002366 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368
2369 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002370 Clang->getTargetOpts().Features = TargetFeatures;
2371 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2372 Clang->getTargetOpts()));
2373 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002374 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002375 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002376 }
2377
2378 // Inform the target of the language options.
2379 //
2380 // FIXME: We shouldn't need to do this, the target should be immutable once
2381 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002382 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002383
Ted Kremenek03201fb2011-03-21 18:40:07 +00002384 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002385 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002386 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002387 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002388 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002389 "IR inputs not support here!");
2390
2391
2392 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002393 Clang->setFileManager(&FileMgr);
2394 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395
2396 // Remap files.
2397 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002398 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002399 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002400 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2401 if (const llvm::MemoryBuffer *
2402 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2403 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2404 OwnedBuffers.push_back(memBuf);
2405 } else {
2406 const char *fname = fileOrBuf.get<const char *>();
2407 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2408 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002409 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002410
Douglas Gregor87c08a52010-08-13 22:48:40 +00002411 // Use the code completion consumer we were given, but adding any cached
2412 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002413 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002414 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002415 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002417 Clang->getFrontendOpts().SkipFunctionBodies = true;
2418
Douglas Gregordf95a132010-08-09 20:45:32 +00002419 // If we have a precompiled preamble, try to use it. We only allow
2420 // the use of the precompiled preamble if we're if the completion
2421 // point is within the main file, after the end of the precompiled
2422 // preamble.
2423 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002424 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002425 using llvm::sys::FileStatus;
2426 llvm::sys::PathWithStatus CompleteFilePath(File);
2427 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2428 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2429 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002430 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2431 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002432 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002433 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002434 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002435 }
2436
2437 // If the main file has been overridden due to the use of a preamble,
2438 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002439 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002440 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002441 stored_diag_begin(),
2442 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002443 if (OverrideMainBuffer) {
2444 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2445 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2446 PreprocessorOpts.PrecompiledPreambleBytes.second
2447 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002448 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002449 PreprocessorOpts.DisablePCHValidation = true;
2450
Douglas Gregor2283d792010-08-20 00:59:43 +00002451 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002452 } else {
2453 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2454 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002455 }
2456
Douglas Gregordca8ee82011-05-06 16:33:08 +00002457 // Disable the preprocessing record
2458 PreprocessorOpts.DetailedRecord = false;
2459
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002460 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002461 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002462 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002463 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002464 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002465 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2466 getSourceManager(), PreambleDiagnostics,
2467 StoredDiagnostics);
2468 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002469 Act->Execute();
2470 Act->EndSourceFile();
2471 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002472
2473 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002474}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002475
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002476bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002477 // Write to a temporary file and later rename it to the actual file, to avoid
2478 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002479 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002480 TempPath = File;
2481 TempPath += "-%%%%%%%%";
2482 int fd;
2483 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2484 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002485 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002486
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002487 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2488 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002489 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002490
2491 serialize(Out);
2492 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002493 if (Out.has_error()) {
2494 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002495 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002496 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002497
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002498 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002499 bool exists;
2500 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002501 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002502 }
2503
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002504 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002505}
2506
Chris Lattner5f9e2722011-07-23 10:55:15 +00002507bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002508 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002509
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002510 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002511 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002512 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002513 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002514 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002515
2516 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002517 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002518 OS.write((char *)&Buffer.front(), Buffer.size());
2519
2520 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002521}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002522
2523typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2524
2525static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2526 unsigned Raw = L.getRawEncoding();
2527 const unsigned MacroBit = 1U << 31;
2528 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2529 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2530}
2531
2532void ASTUnit::TranslateStoredDiagnostics(
2533 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002534 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002535 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 const SmallVectorImpl<StoredDiagnostic> &Diags,
2537 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002538 // The stored diagnostic has the old source manager in it; update
2539 // the locations to refer into the new source manager. We also need to remap
2540 // all the locations to the new view. This includes the diag location, any
2541 // associated source ranges, and the source ranges of associated fix-its.
2542 // FIXME: There should be a cleaner way to do this.
2543
Chris Lattner5f9e2722011-07-23 10:55:15 +00002544 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002545 Result.reserve(Diags.size());
2546 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002547 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002548 assert(Mod && "Don't have preamble module");
2549 SLocRemap &Remap = Mod->SLocRemap;
2550 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2551 // Rebuild the StoredDiagnostic.
2552 const StoredDiagnostic &SD = Diags[I];
2553 SourceLocation L = SD.getLocation();
2554 TranslateSLoc(L, Remap);
2555 FullSourceLoc Loc(L, SrcMgr);
2556
Chris Lattner5f9e2722011-07-23 10:55:15 +00002557 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002558 Ranges.reserve(SD.range_size());
2559 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2560 E = SD.range_end();
2561 I != E; ++I) {
2562 SourceLocation BL = I->getBegin();
2563 TranslateSLoc(BL, Remap);
2564 SourceLocation EL = I->getEnd();
2565 TranslateSLoc(EL, Remap);
2566 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2567 }
2568
Chris Lattner5f9e2722011-07-23 10:55:15 +00002569 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002570 FixIts.reserve(SD.fixit_size());
2571 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2572 E = SD.fixit_end();
2573 I != E; ++I) {
2574 FixIts.push_back(FixItHint());
2575 FixItHint &FH = FixIts.back();
2576 FH.CodeToInsert = I->CodeToInsert;
2577 SourceLocation BL = I->RemoveRange.getBegin();
2578 TranslateSLoc(BL, Remap);
2579 SourceLocation EL = I->RemoveRange.getEnd();
2580 TranslateSLoc(EL, Remap);
2581 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2582 I->RemoveRange.isTokenRange());
2583 }
2584
2585 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2586 SD.getMessage(), Loc, Ranges, FixIts));
2587 }
2588 Result.swap(Out);
2589}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002590
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002591static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2592 std::pair<unsigned, Decl *> R) {
2593 return L.first < R.first;
2594}
2595
2596void ASTUnit::addFileLevelDecl(Decl *D) {
2597 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002598
2599 // We only care about local declarations.
2600 if (D->isFromASTFile())
2601 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002602
2603 SourceManager &SM = *SourceMgr;
2604 SourceLocation Loc = D->getLocation();
2605 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2606 return;
2607
2608 // We only keep track of the file-level declarations of each file.
2609 if (!D->getLexicalDeclContext()->isFileContext())
2610 return;
2611
2612 SourceLocation FileLoc = SM.getFileLoc(Loc);
2613 assert(SM.isLocalSourceLocation(FileLoc));
2614 FileID FID;
2615 unsigned Offset;
2616 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2617 if (FID.isInvalid())
2618 return;
2619
2620 LocDeclsTy *&Decls = FileDecls[FID];
2621 if (!Decls)
2622 Decls = new LocDeclsTy();
2623
2624 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2625
2626 if (Decls->empty() || Decls->back().first <= Offset) {
2627 Decls->push_back(LocDecl);
2628 return;
2629 }
2630
2631 LocDeclsTy::iterator
2632 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2633
2634 Decls->insert(I, LocDecl);
2635}
2636
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002637void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2638 SmallVectorImpl<Decl *> &Decls) {
2639 if (File.isInvalid())
2640 return;
2641
2642 if (SourceMgr->isLoadedFileID(File)) {
2643 assert(Ctx->getExternalSource() && "No external source!");
2644 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2645 Decls);
2646 }
2647
2648 FileDeclsTy::iterator I = FileDecls.find(File);
2649 if (I == FileDecls.end())
2650 return;
2651
2652 LocDeclsTy &LocDecls = *I->second;
2653 if (LocDecls.empty())
2654 return;
2655
2656 LocDeclsTy::iterator
2657 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2658 std::make_pair(Offset, (Decl*)0), compLocDecl);
2659 if (BeginIt != LocDecls.begin())
2660 --BeginIt;
2661
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002662 // If we are pointing at a top-level decl inside an objc container, we need
2663 // to backtrack until we find it otherwise we will fail to report that the
2664 // region overlaps with an objc container.
2665 while (BeginIt != LocDecls.begin() &&
2666 BeginIt->second->isTopLevelDeclInObjCContainer())
2667 --BeginIt;
2668
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002669 LocDeclsTy::iterator
2670 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2671 std::make_pair(Offset+Length, (Decl*)0),
2672 compLocDecl);
2673 if (EndIt != LocDecls.end())
2674 ++EndIt;
2675
2676 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2677 Decls.push_back(DIt->second);
2678}
2679
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002680SourceLocation ASTUnit::getLocation(const FileEntry *File,
2681 unsigned Line, unsigned Col) const {
2682 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002683 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002684 return SM.getMacroArgExpandedLocation(Loc);
2685}
2686
2687SourceLocation ASTUnit::getLocation(const FileEntry *File,
2688 unsigned Offset) const {
2689 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002690 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002691 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2692}
2693
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002694/// \brief If \arg Loc is a loaded location from the preamble, returns
2695/// the corresponding local location of the main file, otherwise it returns
2696/// \arg Loc.
2697SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2698 FileID PreambleID;
2699 if (SourceMgr)
2700 PreambleID = SourceMgr->getPreambleFileID();
2701
2702 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2703 return Loc;
2704
2705 unsigned Offs;
2706 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2707 SourceLocation FileLoc
2708 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2709 return FileLoc.getLocWithOffset(Offs);
2710 }
2711
2712 return Loc;
2713}
2714
2715/// \brief If \arg Loc is a local location of the main file but inside the
2716/// preamble chunk, returns the corresponding loaded location from the
2717/// preamble, otherwise it returns \arg Loc.
2718SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2719 FileID PreambleID;
2720 if (SourceMgr)
2721 PreambleID = SourceMgr->getPreambleFileID();
2722
2723 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2724 return Loc;
2725
2726 unsigned Offs;
2727 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2728 Offs < Preamble.size()) {
2729 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2730 return FileLoc.getLocWithOffset(Offs);
2731 }
2732
2733 return Loc;
2734}
2735
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002736bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2737 FileID FID;
2738 if (SourceMgr)
2739 FID = SourceMgr->getPreambleFileID();
2740
2741 if (Loc.isInvalid() || FID.isInvalid())
2742 return false;
2743
2744 return SourceMgr->isInFileID(Loc, FID);
2745}
2746
2747bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2748 FileID FID;
2749 if (SourceMgr)
2750 FID = SourceMgr->getMainFileID();
2751
2752 if (Loc.isInvalid() || FID.isInvalid())
2753 return false;
2754
2755 return SourceMgr->isInFileID(Loc, FID);
2756}
2757
2758SourceLocation ASTUnit::getEndOfPreambleFileID() {
2759 FileID FID;
2760 if (SourceMgr)
2761 FID = SourceMgr->getPreambleFileID();
2762
2763 if (FID.isInvalid())
2764 return SourceLocation();
2765
2766 return SourceMgr->getLocForEndOfFile(FID);
2767}
2768
2769SourceLocation ASTUnit::getStartOfMainFileID() {
2770 FileID FID;
2771 if (SourceMgr)
2772 FID = SourceMgr->getMainFileID();
2773
2774 if (FID.isInvalid())
2775 return SourceLocation();
2776
2777 return SourceMgr->getLocForStartOfFile(FID);
2778}
2779
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002780std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2781ASTUnit::getLocalPreprocessingEntities() const {
2782 if (isMainFileAST()) {
2783 serialization::ModuleFile &
2784 Mod = Reader->getModuleManager().getPrimaryModule();
2785 return Reader->getModulePreprocessedEntities(Mod);
2786 }
2787
2788 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2789 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2790
2791 return std::make_pair(PreprocessingRecord::iterator(),
2792 PreprocessingRecord::iterator());
2793}
2794
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002795bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002796 if (isMainFileAST()) {
2797 serialization::ModuleFile &
2798 Mod = Reader->getModuleManager().getPrimaryModule();
2799 ASTReader::ModuleDeclIterator MDI, MDE;
2800 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2801 for (; MDI != MDE; ++MDI) {
2802 if (!Fn(context, *MDI))
2803 return false;
2804 }
2805
2806 return true;
2807 }
2808
2809 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2810 TLEnd = top_level_end();
2811 TL != TLEnd; ++TL) {
2812 if (!Fn(context, *TL))
2813 return false;
2814 }
2815
2816 return true;
2817}
2818
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002819void ASTUnit::PreambleData::countLines() const {
2820 NumLines = 0;
2821 if (empty())
2822 return;
2823
2824 for (std::vector<char>::const_iterator
2825 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2826 if (*I == '\n')
2827 ++NumLines;
2828 }
2829 if (Buffer.back() != '\n')
2830 ++NumLines;
2831}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002832
2833#ifndef NDEBUG
2834ASTUnit::ConcurrencyState::ConcurrencyState() {
2835 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2836}
2837
2838ASTUnit::ConcurrencyState::~ConcurrencyState() {
2839 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2840}
2841
2842void ASTUnit::ConcurrencyState::start() {
2843 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2844 assert(acquired && "Concurrent access to ASTUnit!");
2845}
2846
2847void ASTUnit::ConcurrencyState::finish() {
2848 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2849}
2850
2851#else // NDEBUG
2852
2853ASTUnit::ConcurrencyState::ConcurrencyState() {}
2854ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2855void ASTUnit::ConcurrencyState::start() {}
2856void ASTUnit::ConcurrencyState::finish() {}
2857
2858#endif