blob: 8606f686559ea609c9359532d2053a487d9c5662 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000030#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000031#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000049#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000050#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000051#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000052#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000053#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000054#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000055using namespace clang;
56
Douglas Gregor213f18b2010-10-28 15:44:59 +000057using llvm::TimeRecord;
58
59namespace {
60 class SimpleTimer {
61 bool WantTiming;
62 TimeRecord Start;
63 std::string Output;
64
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000066 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Chris Lattner5f9e2722011-07-23 10:55:15 +000071 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000073 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000074 }
75
Douglas Gregor213f18b2010-10-28 15:44:59 +000076 ~SimpleTimer() {
77 if (WantTiming) {
78 TimeRecord Elapsed = TimeRecord::getCurrentTime();
79 Elapsed -= Start;
80 llvm::errs() << Output << ':';
81 Elapsed.print(Elapsed, llvm::errs());
82 llvm::errs() << '\n';
83 }
84 }
85 };
Ted Kremenek1872b312011-10-27 17:55:18 +000086
87 struct OnDiskData {
88 /// \brief The file in which the precompiled preamble is stored.
89 std::string PreambleFile;
90
91 /// \brief Temporary files that should be removed when the ASTUnit is
92 /// destroyed.
93 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
94
95 /// \brief Erase temporary files.
96 void CleanTemporaryFiles();
97
98 /// \brief Erase the preamble file.
99 void CleanPreambleFile();
100
101 /// \brief Erase temporary files and the preamble file.
102 void Cleanup();
103 };
104}
105
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000106static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
107 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
108 return M;
109}
110
Ted Kremenek1872b312011-10-27 17:55:18 +0000111static void cleanupOnDiskMapAtExit(void);
112
113typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
114static OnDiskDataMap &getOnDiskDataMap() {
115 static OnDiskDataMap M;
116 static bool hasRegisteredAtExit = false;
117 if (!hasRegisteredAtExit) {
118 hasRegisteredAtExit = true;
119 atexit(cleanupOnDiskMapAtExit);
120 }
121 return M;
122}
123
124static void cleanupOnDiskMapAtExit(void) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000125 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000126 OnDiskDataMap &M = getOnDiskDataMap();
127 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
128 // We don't worry about freeing the memory associated with OnDiskDataMap.
129 // All we care about is erasing stale files.
130 I->second->Cleanup();
131 }
132}
133
134static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000135 // We require the mutex since we are modifying the structure of the
136 // DenseMap.
137 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000138 OnDiskDataMap &M = getOnDiskDataMap();
139 OnDiskData *&D = M[AU];
140 if (!D)
141 D = new OnDiskData();
142 return *D;
143}
144
145static void erasePreambleFile(const ASTUnit *AU) {
146 getOnDiskData(AU).CleanPreambleFile();
147}
148
149static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000150 // We require the mutex since we are modifying the structure of the
151 // DenseMap.
152 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000153 OnDiskDataMap &M = getOnDiskDataMap();
154 OnDiskDataMap::iterator I = M.find(AU);
155 if (I != M.end()) {
156 I->second->Cleanup();
157 delete I->second;
158 M.erase(AU);
159 }
160}
161
162static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
163 getOnDiskData(AU).PreambleFile = preambleFile;
164}
165
166static const std::string &getPreambleFile(const ASTUnit *AU) {
167 return getOnDiskData(AU).PreambleFile;
168}
169
170void OnDiskData::CleanTemporaryFiles() {
171 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
172 TemporaryFiles[I].eraseFromDisk();
173 TemporaryFiles.clear();
174}
175
176void OnDiskData::CleanPreambleFile() {
177 if (!PreambleFile.empty()) {
178 llvm::sys::Path(PreambleFile).eraseFromDisk();
179 PreambleFile.clear();
180 }
181}
182
183void OnDiskData::Cleanup() {
184 CleanTemporaryFiles();
185 CleanPreambleFile();
186}
187
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000188void ASTUnit::clearFileLevelDecls() {
189 for (FileDeclsTy::iterator
190 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
191 delete I->second;
192 FileDecls.clear();
193}
194
Ted Kremenek1872b312011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
199void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000201}
202
Douglas Gregoreababfb2010-08-04 05:53:38 +0000203/// \brief After failing to build a precompiled preamble (due to
204/// errors in the source that occurs in the preamble), the number of
205/// reparses during which we'll skip even trying to precompile the
206/// preamble.
207const unsigned DefaultPreambleRebuildInterval = 5;
208
Douglas Gregore3c60a72010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000212static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000215 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000216 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000217 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000218 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000219 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000220 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000221 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000222 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000223 CompletionCacheTopLevelHashValue(0),
224 PreambleTopLevelHashValue(0),
225 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000226 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000227 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000228 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000229 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
230 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000231}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000232
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek1872b312011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000243 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (PreprocessorOptions::remapped_file_buffer_iterator
246 FB = PPOpts.remapped_file_buffer_begin(),
247 FBEnd = PPOpts.remapped_file_buffer_end();
248 FB != FBEnd;
249 ++FB)
250 delete FB->second;
251 }
Douglas Gregor28233422010-07-27 14:52:07 +0000252
253 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000254 delete PreambleBuffer;
255
Douglas Gregor213f18b2010-10-28 15:44:59 +0000256 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000257
258 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000259 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000260 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
261 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000262}
263
Douglas Gregor8071e422010-08-15 06:18:01 +0000264/// \brief Determine the set of code-completion contexts in which this
265/// declaration should be shown.
266static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000267 const LangOptions &LangOpts,
268 bool &IsNestedNameSpecifier) {
269 IsNestedNameSpecifier = false;
270
Douglas Gregor8071e422010-08-15 06:18:01 +0000271 if (isa<UsingShadowDecl>(ND))
272 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
273 if (!ND)
274 return 0;
275
276 unsigned Contexts = 0;
277 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
278 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
279 // Types can appear in these contexts.
280 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
281 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
282 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
283 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
284 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000285 | (1 << (CodeCompletionContext::CCC_Type - 1))
286 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000287
288 // In C++, types can appear in expressions contexts (for functional casts).
289 if (LangOpts.CPlusPlus)
290 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
291
292 // In Objective-C, message sends can send interfaces. In Objective-C++,
293 // all types are available due to functional casts.
294 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
295 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000296
297 // In Objective-C, you can only be a subclass of another Objective-C class
298 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000299 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000300
301 // Deal with tag names.
302 if (isa<EnumDecl>(ND)) {
303 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
304
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000305 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000306 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000307 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000308 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
309 if (Record->isUnion())
310 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
311 else
312 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
313
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000316 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000318 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
319 // Values can appear in these contexts.
320 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
321 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000322 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
324 } else if (isa<ObjCProtocolDecl>(ND)) {
325 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000326 } else if (isa<ObjCCategoryDecl>(ND)) {
327 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000328 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000330
331 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000332 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000333 }
334
335 return Contexts;
336}
337
Douglas Gregor87c08a52010-08-13 22:48:40 +0000338void ASTUnit::CacheCodeCompletionResults() {
339 if (!TheSema)
340 return;
341
Douglas Gregor213f18b2010-10-28 15:44:59 +0000342 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000343 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000344
345 // Clear out the previous results.
346 ClearCachedCompletionResults();
347
348 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000349 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000351 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
352 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000353
354 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
356
Douglas Gregor87c08a52010-08-13 22:48:40 +0000357 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
358 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000359 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000360 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000361 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000362 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000364 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000365 Ctx->getLangOptions(),
366 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 CachedResult.Priority = Results[I].Priority;
368 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000369 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000370
Douglas Gregorf5586f62010-08-16 18:08:11 +0000371 // Keep track of the type of this completion in an ASTContext-agnostic
372 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000373 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000375 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000376 CachedResult.Type = 0;
377 } else {
378 CanQualType CanUsageType
379 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
380 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
381
382 // Determine whether we have already seen this type. If so, we save
383 // ourselves the work of formatting the type string by using the
384 // temporary, CanQualType-based hash table to find the associated value.
385 unsigned &TypeValue = CompletionTypes[CanUsageType];
386 if (TypeValue == 0) {
387 TypeValue = CompletionTypes.size();
388 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
389 = TypeValue;
390 }
391
392 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000393 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000394
Douglas Gregor8071e422010-08-15 06:18:01 +0000395 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000396
397 /// Handle nested-name-specifiers in C++.
398 if (TheSema->Context.getLangOptions().CPlusPlus &&
399 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
400 // The contexts in which a nested-name-specifier can appear in C++.
401 unsigned NNSContexts
402 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
403 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
404 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
405 | (1 << (CodeCompletionContext::CCC_Statement - 1))
406 | (1 << (CodeCompletionContext::CCC_Expression - 1))
407 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
408 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
409 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
410 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000411 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000412 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
413 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000414
415 if (isa<NamespaceDecl>(Results[I].Declaration) ||
416 isa<NamespaceAliasDecl>(Results[I].Declaration))
417 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
418
419 if (unsigned RemainingContexts
420 = NNSContexts & ~CachedResult.ShowInContexts) {
421 // If there any contexts where this completion can be a
422 // nested-name-specifier but isn't already an option, create a
423 // nested-name-specifier completion.
424 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000425 CachedResult.Completion
426 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000427 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000428 CachedResult.ShowInContexts = RemainingContexts;
429 CachedResult.Priority = CCP_NestedNameSpecifier;
430 CachedResult.TypeClass = STC_Void;
431 CachedResult.Type = 0;
432 CachedCompletionResults.push_back(CachedResult);
433 }
434 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000435 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000436 }
437
Douglas Gregor87c08a52010-08-13 22:48:40 +0000438 case Result::RK_Keyword:
439 case Result::RK_Pattern:
440 // Ignore keywords and patterns; we don't care, since they are so
441 // easily regenerated.
442 break;
443
444 case Result::RK_Macro: {
445 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000446 CachedResult.Completion
447 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000448 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 CachedResult.ShowInContexts
450 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
451 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
453 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
454 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
455 | (1 << (CodeCompletionContext::CCC_Statement - 1))
456 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000457 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000458 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000459 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000460 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
461 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000462
Douglas Gregor87c08a52010-08-13 22:48:40 +0000463 CachedResult.Priority = Results[I].Priority;
464 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000465 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000466 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000467 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000468 CachedCompletionResults.push_back(CachedResult);
469 break;
470 }
471 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000472 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000473
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476}
477
478void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000479 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000481 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482}
483
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000484namespace {
485
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000486/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000488class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000489 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000490 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
492 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000493 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494 std::string &Predefines;
495 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000499 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000501 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
502 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000503 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
504 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000506 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000507 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000508 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000512 return false;
513
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000515
516 // Initialize the preprocessor.
517 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518
519 // Initialize the ASTContext
520 Context.InitBuiltinTypes(*Target);
521
522 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner5f9e2722011-07-23 10:55:15 +0000526 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000527 // If we've already initialized the target, don't do it again.
528 if (Target)
529 return false;
530
531 // FIXME: This is broken, we should store the TargetOptions in the AST file.
532 TargetOptions TargetOpts;
533 TargetOpts.ABI = "";
534 TargetOpts.CXXABI = "";
535 TargetOpts.CPU = "";
536 TargetOpts.Features.clear();
537 TargetOpts.Triple = Triple;
538 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000539 return false;
540 }
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000542 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000543 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000544 std::string &SuggestedPredefines,
545 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000546 Predefines = Buffers[0].Data;
547 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
548 Predefines += Buffers[I].Data;
549 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000553 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000557 virtual void ReadCounter(unsigned Value) {
558 Counter = Value;
559 }
560};
561
David Blaikie26e7a902011-09-26 00:01:39 +0000562class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000563 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000564
565public:
David Blaikie26e7a902011-09-26 00:01:39 +0000566 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000567 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000568 : StoredDiags(StoredDiags) { }
569
David Blaikied6471f72011-09-25 23:23:43 +0000570 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000571 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000572
573 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
574 // Just drop any diagnostics that come from cloned consumers; they'll
575 // have different source managers anyway.
576 return new IgnoringDiagConsumer();
577 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000578};
579
580/// \brief RAII object that optionally captures diagnostics, if
581/// there is no diagnostic client to capture them already.
582class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000583 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000584 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000585 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000586
587public:
David Blaikied6471f72011-09-25 23:23:43 +0000588 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000590 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000591 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000592 if (RequestCapture || Diags.getClient() == 0) {
593 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000594 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000595 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000596 }
597
598 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000599 if (Diags.getClient() == &Client) {
600 Diags.takeClient();
601 Diags.setClient(PreviousClient);
602 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000603 }
604};
605
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000606} // anonymous namespace
607
David Blaikie26e7a902011-09-26 00:01:39 +0000608void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000609 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000610 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000611 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000612
Douglas Gregora88084b2010-02-18 18:08:43 +0000613 StoredDiags.push_back(StoredDiagnostic(Level, Info));
614}
615
Steve Naroff77accc12009-09-03 18:19:54 +0000616const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000617 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000618}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000619
Chris Lattner5f9e2722011-07-23 10:55:15 +0000620llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000621 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000622 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000623 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000624}
625
Douglas Gregore47be3e2010-11-11 00:39:14 +0000626/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikied6471f72011-09-25 23:23:43 +0000627void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000628 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000629 ASTUnit &AST, bool CaptureDiagnostics) {
630 if (!Diags.getPtr()) {
631 // No diagnostics engine was provided, so create our own diagnostics object
632 // with the default options.
633 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000634 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000635 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000636 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000637 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
638 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000639 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000640 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000641 }
642}
643
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000644ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikied6471f72011-09-25 23:23:43 +0000645 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000646 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000647 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000648 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000649 unsigned NumRemappedFiles,
650 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000651 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000652
653 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000654 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
655 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000656 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
657 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000658 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000659
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000660 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000661
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000662 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000663 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000664 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000665 AST->FileMgr = new FileManager(FileSystemOpts);
666 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
667 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000668 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
669 AST->getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000670
Douglas Gregor4db64a42010-01-23 00:14:00 +0000671 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000672 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
673 if (const llvm::MemoryBuffer *
674 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
675 // Create the file entry for the file that we're mapping from.
676 const FileEntry *FromFile
677 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
678 memBuf->getBufferSize(),
679 0);
680 if (!FromFile) {
681 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
682 << RemappedFiles[I].first;
683 delete memBuf;
684 continue;
685 }
686
687 // Override the contents of the "from" file with the contents of
688 // the "to" file.
689 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
690
691 } else {
692 const char *fname = fileOrBuf.get<const char *>();
693 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
694 if (!ToFile) {
695 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
696 << RemappedFiles[I].first << fname;
697 continue;
698 }
699
700 // Create the file entry for the file that we're mapping from.
701 const FileEntry *FromFile
702 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
703 ToFile->getSize(),
704 0);
705 if (!FromFile) {
706 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
707 << RemappedFiles[I].first;
708 delete memBuf;
709 continue;
710 }
711
712 // Override the contents of the "from" file with the contents of
713 // the "to" file.
714 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000715 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000716 }
717
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000718 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000720 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000721 std::string Predefines;
722 unsigned Counter;
723
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000724 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000725
Douglas Gregor998b3d32011-09-01 23:39:15 +0000726 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
727 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
728 *AST,
729 /*IILookup=*/0,
730 /*OwnsHeaderSearch=*/false,
731 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000732 Preprocessor &PP = *AST->PP;
733
734 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
735 AST->getSourceManager(),
736 /*Target=*/0,
737 PP.getIdentifierTable(),
738 PP.getSelectorTable(),
739 PP.getBuiltinInfo(),
740 /* size_reserve = */0,
741 /*DelayInitialization=*/true);
742 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000743
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000744 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000745
746 // Recover resources if we crash before exiting this method.
747 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
748 ReaderCleanup(Reader.get());
749
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000750 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000751 AST->ASTFileLangOpts, HeaderInfo,
752 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000753
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000754 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000755 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000756 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000758 case ASTReader::Failure:
759 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000760 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000761 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000764 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
765
Daniel Dunbard5b61262009-09-21 03:03:47 +0000766 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000767 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000769 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000770 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000771 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000772 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000773 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000774
775 // Unregister the cleanup for ASTReader. It will get cleaned up
776 // by the ASTUnit cleanup.
777 ReaderCleanup.unregister();
778
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000779 Context.setExternalSource(Source);
780
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000781 // Create an AST consumer, even though it isn't used.
782 AST->Consumer.reset(new ASTConsumer);
783
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000784 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000785 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
786 AST->TheSema->Initialize();
787 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000788 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000789
Mike Stump1eb44332009-09-09 15:08:12 +0000790 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000791}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000792
793namespace {
794
Douglas Gregor9b7db622011-02-16 18:16:54 +0000795/// \brief Preprocessor callback class that updates a hash value with the names
796/// of all macros that have been defined by the translation unit.
797class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
798 unsigned &Hash;
799
800public:
801 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
802
803 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
804 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
805 }
806};
807
808/// \brief Add the given declaration to the hash of all top-level entities.
809void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
810 if (!D)
811 return;
812
813 DeclContext *DC = D->getDeclContext();
814 if (!DC)
815 return;
816
817 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
818 return;
819
820 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
821 if (ND->getIdentifier())
822 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
823 else if (DeclarationName Name = ND->getDeclName()) {
824 std::string NameStr = Name.getAsString();
825 Hash = llvm::HashString(NameStr, Hash);
826 }
827 return;
828 }
829
830 if (ObjCForwardProtocolDecl *Forward
831 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
832 for (ObjCForwardProtocolDecl::protocol_iterator
833 P = Forward->protocol_begin(),
834 PEnd = Forward->protocol_end();
835 P != PEnd; ++P)
836 AddTopLevelDeclarationToHash(*P, Hash);
837 return;
838 }
839
Chris Lattner5f9e2722011-07-23 10:55:15 +0000840 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000841 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregor9b7db622011-02-16 18:16:54 +0000842 return;
843 }
844}
845
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000846class TopLevelDeclTrackerConsumer : public ASTConsumer {
847 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000848 unsigned &Hash;
849
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000850public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000851 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
852 : Unit(_Unit), Hash(Hash) {
853 Hash = 0;
854 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000855
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000856 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000857 if (!D)
858 return;
859
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000860 // FIXME: Currently ObjC method declarations are incorrectly being
861 // reported as top-level declarations, even though their DeclContext
862 // is the containing ObjC @interface/@implementation. This is a
863 // fundamental problem in the parser right now.
864 if (isa<ObjCMethodDecl>(D))
865 return;
866
867 AddTopLevelDeclarationToHash(D, Hash);
868 Unit.addTopLevelDecl(D);
869
870 handleFileLevelDecl(D);
871 }
872
873 void handleFileLevelDecl(Decl *D) {
874 Unit.addFileLevelDecl(D);
875 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
876 for (NamespaceDecl::decl_iterator
877 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
878 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000879 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000880 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000881
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000882 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000883 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
884 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000885 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000886 }
887
Sebastian Redl27372b42010-08-11 18:52:41 +0000888 // We're not interested in "interesting" decls.
889 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000890
891 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
892 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
893 handleTopLevelDecl(*it);
894 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000895};
896
897class TopLevelDeclTrackerAction : public ASTFrontendAction {
898public:
899 ASTUnit &Unit;
900
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000902 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000903 CI.getPreprocessor().addPPCallbacks(
904 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
905 return new TopLevelDeclTrackerConsumer(Unit,
906 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000907 }
908
909public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000910 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
911
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000912 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000913 virtual TranslationUnitKind getTranslationUnitKind() {
914 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000915 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000916};
917
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000918class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000919 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000920 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000921 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000922
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000923public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000924 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000925 StringRef isysroot, raw_ostream *Out)
Douglas Gregor7143aab2011-09-01 17:04:32 +0000926 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000927 Hash(Unit.getCurrentTopLevelHashValue()) {
928 Hash = 0;
929 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000930
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000931 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000932 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
933 Decl *D = *it;
934 // FIXME: Currently ObjC method declarations are incorrectly being
935 // reported as top-level declarations, even though their DeclContext
936 // is the containing ObjC @interface/@implementation. This is a
937 // fundamental problem in the parser right now.
938 if (isa<ObjCMethodDecl>(D))
939 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000940 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000941 TopLevelDecls.push_back(D);
942 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000943 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000944 }
945
946 virtual void HandleTranslationUnit(ASTContext &Ctx) {
947 PCHGenerator::HandleTranslationUnit(Ctx);
948 if (!Unit.getDiagnostics().hasErrorOccurred()) {
949 // Translate the top-level declarations we captured during
950 // parsing into declaration IDs in the precompiled
951 // preamble. This will allow us to deserialize those top-level
952 // declarations when requested.
953 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
954 Unit.addTopLevelDeclFromPreamble(
955 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000956 }
957 }
958};
959
960class PrecompilePreambleAction : public ASTFrontendAction {
961 ASTUnit &Unit;
962
963public:
964 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
965
966 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000967 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000968 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000969 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000970 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000971 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
972 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000973 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000974 return 0;
975
Douglas Gregor832d6202011-07-22 16:35:34 +0000976 if (!CI.getFrontendOpts().RelocatablePCH)
977 Sysroot.clear();
978
Douglas Gregor9b7db622011-02-16 18:16:54 +0000979 CI.getPreprocessor().addPPCallbacks(
980 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000981 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
982 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000983 }
984
985 virtual bool hasCodeCompletionSupport() const { return false; }
986 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000987 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000988};
989
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000990}
991
Douglas Gregorabc563f2010-07-19 21:46:24 +0000992/// Parse the source file into a translation unit using the given compiler
993/// invocation, replacing the current translation unit.
994///
995/// \returns True if a failure occurred that causes the ASTUnit not to
996/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000997bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000998 delete SavedMainFileBuffer;
999 SavedMainFileBuffer = 0;
1000
Ted Kremenek4f327862011-03-21 18:40:17 +00001001 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001002 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001003 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001004 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001005
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001006 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001007 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1008
1009 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001010 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1011 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001012
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001013 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1014 CCInvocation(new CompilerInvocation(*Invocation));
1015
1016 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001017 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001018
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001019 // Set up diagnostics, capturing any diagnostics that would
1020 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001021 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001022
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001023 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001024 Clang->getTargetOpts().Features = TargetFeatures;
1025 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001026 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001027 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001028 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001029 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001030 }
1031
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001032 // Inform the target of the language options.
1033 //
1034 // FIXME: We shouldn't need to do this, the target should be immutable once
1035 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001036 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001037
Ted Kremenek03201fb2011-03-21 18:40:07 +00001038 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001039 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001040 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001041 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001042 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001043 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001044
Douglas Gregorabc563f2010-07-19 21:46:24 +00001045 // Configure the various subsystems.
1046 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001047 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001048 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001049 FileMgr = new FileManager(FileSystemOpts);
1050 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001051 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001052 Ctx = 0;
1053 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001054 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001055
1056 // Clear out old caches and data.
1057 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001058 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001059 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001060
Douglas Gregorf128fed2010-08-20 00:02:33 +00001061 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001062 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf128fed2010-08-20 00:02:33 +00001063 TopLevelDeclsInPreamble.clear();
1064 }
1065
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001066 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001067 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001068
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001069 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001070 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001071
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001072 // If the main file has been overridden due to the use of a preamble,
1073 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001074 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +00001075 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1076 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001077 if (OverrideMainBuffer) {
1078 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1079 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1080 PreprocessorOpts.PrecompiledPreambleBytes.second
1081 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001082 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001083 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001084
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001085 // The stored diagnostic has the old source manager in it; update
1086 // the locations to refer into the new source manager. Since we've
1087 // been careful to make sure that the source manager's state
1088 // before and after are identical, so that we can reuse the source
1089 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001090 for (unsigned I = NumStoredDiagnosticsFromDriver,
1091 N = StoredDiagnostics.size();
1092 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001093 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1094 getSourceManager());
1095 StoredDiagnostics[I].setLocation(Loc);
1096 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001097
1098 // Keep track of the override buffer;
1099 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001100 }
1101
Ted Kremenek25a11e12011-03-22 01:15:24 +00001102 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1103 new TopLevelDeclTrackerAction(*this));
1104
1105 // Recover resources if we crash before exiting this method.
1106 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1107 ActCleanup(Act.get());
1108
Ted Kremenek03201fb2011-03-21 18:40:07 +00001109 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1110 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001111 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001112
1113 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001114 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001115 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1116 getSourceManager(), PreambleDiagnostics,
1117 StoredDiagnostics);
1118 }
1119
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001120 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001121
Ted Kremenek4f327862011-03-21 18:40:17 +00001122 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001123 TheSema.reset(Clang->takeSema());
1124 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001125 Ctx = &Clang->getASTContext();
1126 PP = &Clang->getPreprocessor();
1127 Clang->setSourceManager(0);
1128 Clang->setFileManager(0);
1129 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001130 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001132 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001133
Douglas Gregorabc563f2010-07-19 21:46:24 +00001134 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001135
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001136error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001137 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001138 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001139 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001140 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001141 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001142
Douglas Gregord54eb442010-10-12 16:25:54 +00001143 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001144 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145 return true;
1146}
1147
Douglas Gregor44c181a2010-07-23 00:33:23 +00001148/// \brief Simple function to retrieve a path for a preamble precompiled header.
1149static std::string GetPreamblePCHPath() {
1150 // FIXME: This is lame; sys::Path should provide this function (in particular,
1151 // it should know how to find the temporary files dir).
1152 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001153 // FIXME: This is a hack so that we can override the preamble file during
1154 // crash-recovery testing, which is the only case where the preamble files
1155 // are not necessarily cleaned up.
1156 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1157 if (TmpFile)
1158 return TmpFile;
1159
Douglas Gregor44c181a2010-07-23 00:33:23 +00001160 std::string Error;
1161 const char *TmpDir = ::getenv("TMPDIR");
1162 if (!TmpDir)
1163 TmpDir = ::getenv("TEMP");
1164 if (!TmpDir)
1165 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001166#ifdef LLVM_ON_WIN32
1167 if (!TmpDir)
1168 TmpDir = ::getenv("USERPROFILE");
1169#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001170 if (!TmpDir)
1171 TmpDir = "/tmp";
1172 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001173 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001174 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001175 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001176 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001177 return std::string();
1178
Douglas Gregor44c181a2010-07-23 00:33:23 +00001179 return P.str();
1180}
1181
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001182/// \brief Compute the preamble for the main file, providing the source buffer
1183/// that corresponds to the main file along with a pair (bytes, start-of-line)
1184/// that describes the preamble.
1185std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001186ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1187 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001188 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001189 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001190 CreatedBuffer = false;
1191
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 // Try to determine if the main file has been remapped, either from the
1193 // command line (to another file) or directly through the compiler invocation
1194 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001195 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001196 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1197 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1198 // Check whether there is a file-file remapping of the main file
1199 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001200 M = PreprocessorOpts.remapped_file_begin(),
1201 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202 M != E;
1203 ++M) {
1204 llvm::sys::PathWithStatus MPath(M->first);
1205 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1206 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1207 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001208 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001209 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 CreatedBuffer = false;
1211 }
1212
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001213 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001215 return std::make_pair((llvm::MemoryBuffer*)0,
1216 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001217 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001218 }
1219 }
1220 }
1221
1222 // Check whether there is a file-buffer remapping. It supercedes the
1223 // file-file remapping.
1224 for (PreprocessorOptions::remapped_file_buffer_iterator
1225 M = PreprocessorOpts.remapped_file_buffer_begin(),
1226 E = PreprocessorOpts.remapped_file_buffer_end();
1227 M != E;
1228 ++M) {
1229 llvm::sys::PathWithStatus MPath(M->first);
1230 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1231 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1232 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001233 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001235 CreatedBuffer = false;
1236 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237
Douglas Gregor175c4a92010-07-23 23:58:40 +00001238 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001239 }
1240 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001241 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 }
1243
1244 // If the main source file was not remapped, load it now.
1245 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001246 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001247 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001248 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249
1250 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 }
1252
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001253 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001254 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001255 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256}
1257
Douglas Gregor754f3492010-07-24 00:38:13 +00001258static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001259 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001260 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001261 llvm::MemoryBuffer *Result
1262 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1263 memcpy(const_cast<char*>(Result->getBufferStart()),
1264 Old->getBufferStart(), Old->getBufferSize());
1265 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001266 ' ', NewSize - Old->getBufferSize() - 1);
1267 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001268
Douglas Gregor754f3492010-07-24 00:38:13 +00001269 return Result;
1270}
1271
Douglas Gregor175c4a92010-07-23 23:58:40 +00001272/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1273/// the source file.
1274///
1275/// This routine will compute the preamble of the main source file. If a
1276/// non-trivial preamble is found, it will precompile that preamble into a
1277/// precompiled header so that the precompiled preamble can be used to reduce
1278/// reparsing time. If a precompiled preamble has already been constructed,
1279/// this routine will determine if it is still valid and, if so, avoid
1280/// rebuilding the precompiled preamble.
1281///
Douglas Gregordf95a132010-08-09 20:45:32 +00001282/// \param AllowRebuild When true (the default), this routine is
1283/// allowed to rebuild the precompiled preamble if it is found to be
1284/// out-of-date.
1285///
1286/// \param MaxLines When non-zero, the maximum number of lines that
1287/// can occur within the preamble.
1288///
Douglas Gregor754f3492010-07-24 00:38:13 +00001289/// \returns If the precompiled preamble can be used, returns a newly-allocated
1290/// buffer that should be used in place of the main file when doing so.
1291/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001292llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001293 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001294 bool AllowRebuild,
1295 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001296
1297 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1298 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1299 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001300 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001301 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302
1303 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001304 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001305 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001306
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001307 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001308 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1309 if (CreatedPreambleBuffer)
1310 OwnedPreambleBuffer.reset(NewPreamble.first);
1311
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001312 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001313 // We couldn't find a preamble in the main source. Clear out the current
1314 // preamble, if we have one. It's obviously no good any more.
1315 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001316 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001317
1318 // The next time we actually see a preamble, precompile it.
1319 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001320 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001321 }
1322
1323 if (!Preamble.empty()) {
1324 // We've previously computed a preamble. Check whether we have the same
1325 // preamble now that we did before, and that there's enough space in
1326 // the main-file buffer within the precompiled preamble to fit the
1327 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001328 if (Preamble.size() == NewPreamble.second.first &&
1329 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001330 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001331 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001332 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001333 // The preamble has not changed. We may be able to re-use the precompiled
1334 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001335
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001336 // Check that none of the files used by the preamble have changed.
1337 bool AnyFileChanged = false;
1338
1339 // First, make a record of those files that have been overridden via
1340 // remapping or unsaved_files.
1341 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1342 for (PreprocessorOptions::remapped_file_iterator
1343 R = PreprocessorOpts.remapped_file_begin(),
1344 REnd = PreprocessorOpts.remapped_file_end();
1345 !AnyFileChanged && R != REnd;
1346 ++R) {
1347 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001348 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001349 // If we can't stat the file we're remapping to, assume that something
1350 // horrible happened.
1351 AnyFileChanged = true;
1352 break;
1353 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001354
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001355 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1356 StatBuf.st_mtime);
1357 }
1358 for (PreprocessorOptions::remapped_file_buffer_iterator
1359 R = PreprocessorOpts.remapped_file_buffer_begin(),
1360 REnd = PreprocessorOpts.remapped_file_buffer_end();
1361 !AnyFileChanged && R != REnd;
1362 ++R) {
1363 // FIXME: Should we actually compare the contents of file->buffer
1364 // remappings?
1365 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1366 0);
1367 }
1368
1369 // Check whether anything has changed.
1370 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1371 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1372 !AnyFileChanged && F != FEnd;
1373 ++F) {
1374 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1375 = OverriddenFiles.find(F->first());
1376 if (Overridden != OverriddenFiles.end()) {
1377 // This file was remapped; check whether the newly-mapped file
1378 // matches up with the previous mapping.
1379 if (Overridden->second != F->second)
1380 AnyFileChanged = true;
1381 continue;
1382 }
1383
1384 // The file was not remapped; check whether it has changed on disk.
1385 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001386 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001387 // If we can't stat the file, assume that something horrible happened.
1388 AnyFileChanged = true;
1389 } else if (StatBuf.st_size != F->second.first ||
1390 StatBuf.st_mtime != F->second.second)
1391 AnyFileChanged = true;
1392 }
1393
1394 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001395 // Okay! We can re-use the precompiled preamble.
1396
1397 // Set the state of the diagnostic object to mimic its state
1398 // after parsing the preamble.
1399 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001400 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001401 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001402 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001403
1404 // Create a version of the main file buffer that is padded to
1405 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001406 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001407 PreambleReservedSize,
1408 FrontendOpts.Inputs[0].second);
1409 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001410 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001411
1412 // If we aren't allowed to rebuild the precompiled preamble, just
1413 // return now.
1414 if (!AllowRebuild)
1415 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001416
Douglas Gregor175c4a92010-07-23 23:58:40 +00001417 // We can't reuse the previously-computed preamble. Build a new one.
1418 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001419 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001420 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001421 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001422 } else if (!AllowRebuild) {
1423 // We aren't allowed to rebuild the precompiled preamble; just
1424 // return now.
1425 return 0;
1426 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001427
1428 // If the preamble rebuild counter > 1, it's because we previously
1429 // failed to build a preamble and we're not yet ready to try
1430 // again. Decrement the counter and return a failure.
1431 if (PreambleRebuildCounter > 1) {
1432 --PreambleRebuildCounter;
1433 return 0;
1434 }
1435
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001436 // Create a temporary file for the precompiled preamble. In rare
1437 // circumstances, this can fail.
1438 std::string PreamblePCHPath = GetPreamblePCHPath();
1439 if (PreamblePCHPath.empty()) {
1440 // Try again next time.
1441 PreambleRebuildCounter = 1;
1442 return 0;
1443 }
1444
Douglas Gregor175c4a92010-07-23 23:58:40 +00001445 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001446 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001447 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001448
1449 // Create a new buffer that stores the preamble. The buffer also contains
1450 // extra space for the original contents of the file (which will be present
1451 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001452 // grows.
1453 PreambleReservedSize = NewPreamble.first->getBufferSize();
1454 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001455 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001456 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001457 PreambleReservedSize *= 2;
1458
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001459 // Save the preamble text for later; we'll need to compare against it for
1460 // subsequent reparses.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001461 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1462 Preamble.assign(FileMgr->getFile(MainFilename),
1463 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001464 NewPreamble.first->getBufferStart()
1465 + NewPreamble.second.first);
1466 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1467
Douglas Gregor671947b2010-08-19 01:33:06 +00001468 delete PreambleBuffer;
1469 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001470 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001471 FrontendOpts.Inputs[0].second);
1472 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001473 NewPreamble.first->getBufferStart(), Preamble.size());
1474 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001475 ' ', PreambleReservedSize - Preamble.size() - 1);
1476 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001477
1478 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001479 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001480 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1481
1482 // Tell the compiler invocation to generate a temporary precompiled header.
1483 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001484 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001485 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001486 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1487 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001488
1489 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001490 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1491
1492 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001493 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1494 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001495
Douglas Gregor01b6e312011-07-01 18:22:13 +00001496 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001497 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001498
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001499 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001500 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001501
1502 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001503 Clang->getTargetOpts().Features = TargetFeatures;
1504 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1505 Clang->getTargetOpts()));
1506 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001507 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1508 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001509 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001510 PreprocessorOpts.eraseRemappedFile(
1511 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001512 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001513 }
1514
1515 // Inform the target of the language options.
1516 //
1517 // FIXME: We shouldn't need to do this, the target should be immutable once
1518 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001519 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520
Ted Kremenek03201fb2011-03-21 18:40:07 +00001521 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001523 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001525 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526 "IR inputs not support here!");
1527
1528 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001529 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001530 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001531 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001532 TopLevelDecls.clear();
1533 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534
1535 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001536 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537
1538 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001540 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001542 llvm::OwningPtr<PrecompilePreambleAction> Act;
1543 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001544 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1545 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001546 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1547 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001548 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001549 PreprocessorOpts.eraseRemappedFile(
1550 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001551 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552 }
1553
1554 Act->Execute();
1555 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001556
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001557 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001558 // There were errors parsing the preamble, so no precompiled header was
1559 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001560 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001561 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1562 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001563 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001564 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001565 PreprocessorOpts.eraseRemappedFile(
1566 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001567 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001568 }
1569
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001570 // Transfer any diagnostics generated when parsing the preamble into the set
1571 // of preamble diagnostics.
1572 PreambleDiagnostics.clear();
1573 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001574 stored_diag_afterDriver_begin(), stored_diag_end());
1575 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001576
Douglas Gregor175c4a92010-07-23 23:58:40 +00001577 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001578 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001579 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001580
1581 // Keep track of all of the files that the source manager knows about,
1582 // so we can verify whether they have changed or not.
1583 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001584 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001585 const llvm::MemoryBuffer *MainFileBuffer
1586 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1587 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1588 FEnd = SourceMgr.fileinfo_end();
1589 F != FEnd;
1590 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001591 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001592 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1593 continue;
1594
1595 FilesInPreamble[File->getName()]
1596 = std::make_pair(F->second->getSize(), File->getModificationTime());
1597 }
1598
Douglas Gregoreababfb2010-08-04 05:53:38 +00001599 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001600 PreprocessorOpts.eraseRemappedFile(
1601 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001602
1603 // If the hash of top-level entities differs from the hash of the top-level
1604 // entities the last time we rebuilt the preamble, clear out the completion
1605 // cache.
1606 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1607 CompletionCacheTopLevelHashValue = 0;
1608 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1609 }
1610
Douglas Gregor754f3492010-07-24 00:38:13 +00001611 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001612 PreambleReservedSize,
1613 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001614}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001615
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001616void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1617 std::vector<Decl *> Resolved;
1618 Resolved.reserve(TopLevelDeclsInPreamble.size());
1619 ExternalASTSource &Source = *getASTContext().getExternalSource();
1620 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1621 // Resolve the declaration ID to an actual declaration, possibly
1622 // deserializing the declaration in the process.
1623 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1624 if (D)
1625 Resolved.push_back(D);
1626 }
1627 TopLevelDeclsInPreamble.clear();
1628 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1629}
1630
Chris Lattner5f9e2722011-07-23 10:55:15 +00001631StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001632 return Invocation->getFrontendOpts().Inputs[0].second;
1633}
1634
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001635ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001636 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1637 bool CaptureDiagnostics) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001638 llvm::OwningPtr<ASTUnit> AST;
1639 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001640 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001641 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001642 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001643 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001644 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001645 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001646
1647 return AST.take();
1648}
1649
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001650ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001651 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001652 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001653 ASTUnit *Unit,
1654 bool Persistent,
1655 StringRef ResourceFilesPath,
1656 bool OnlyLocalDecls,
1657 bool CaptureDiagnostics,
1658 bool PrecompilePreamble,
1659 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001660 assert(CI && "A CompilerInvocation is required");
1661
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001662 llvm::OwningPtr<ASTUnit> OwnAST;
1663 ASTUnit *AST = Unit;
1664 if (!AST) {
1665 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001666 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001667 AST = OwnAST.get();
1668 }
1669
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001670 if (!ResourceFilesPath.empty()) {
1671 // Override the resources path.
1672 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1673 }
1674 AST->OnlyLocalDecls = OnlyLocalDecls;
1675 AST->CaptureDiagnostics = CaptureDiagnostics;
1676 if (PrecompilePreamble)
1677 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001678 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001679 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001680
1681 // Recover resources if we crash before exiting this method.
1682 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001683 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001684 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1685 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001686 DiagCleanup(Diags.getPtr());
1687
1688 // We'll manage file buffers ourselves.
1689 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1690 CI->getFrontendOpts().DisableFree = false;
1691 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1692
1693 // Save the target features.
1694 AST->TargetFeatures = CI->getTargetOpts().Features;
1695
1696 // Create the compiler instance to use for building the AST.
1697 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1698
1699 // Recover resources if we crash before exiting this method.
1700 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1701 CICleanup(Clang.get());
1702
1703 Clang->setInvocation(CI);
1704 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1705
1706 // Set up diagnostics, capturing any diagnostics that would
1707 // otherwise be dropped.
1708 Clang->setDiagnostics(&AST->getDiagnostics());
1709
1710 // Create the target instance.
1711 Clang->getTargetOpts().Features = AST->TargetFeatures;
1712 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1713 Clang->getTargetOpts()));
1714 if (!Clang->hasTarget())
1715 return 0;
1716
1717 // Inform the target of the language options.
1718 //
1719 // FIXME: We shouldn't need to do this, the target should be immutable once
1720 // created. This complexity should be lifted elsewhere.
1721 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1722
1723 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1724 "Invocation must have exactly one source file!");
1725 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1726 "FIXME: AST inputs not yet supported here!");
1727 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1728 "IR inputs not supported here!");
1729
1730 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001731 AST->TheSema.reset();
1732 AST->Ctx = 0;
1733 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001734 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001735
1736 // Create a file manager object to provide access to and cache the filesystem.
1737 Clang->setFileManager(&AST->getFileManager());
1738
1739 // Create the source manager.
1740 Clang->setSourceManager(&AST->getSourceManager());
1741
1742 ASTFrontendAction *Act = Action;
1743
1744 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1745 if (!Act) {
1746 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1747 Act = TrackerAct.get();
1748 }
1749
1750 // Recover resources if we crash before exiting this method.
1751 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1752 ActCleanup(TrackerAct.get());
1753
1754 if (!Act->BeginSourceFile(*Clang.get(),
1755 Clang->getFrontendOpts().Inputs[0].second,
1756 Clang->getFrontendOpts().Inputs[0].first))
1757 return 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001758
1759 if (Persistent && !TrackerAct) {
1760 Clang->getPreprocessor().addPPCallbacks(
1761 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1762 std::vector<ASTConsumer*> Consumers;
1763 if (Clang->hasASTConsumer())
1764 Consumers.push_back(Clang->takeASTConsumer());
1765 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1766 AST->getCurrentTopLevelHashValue()));
1767 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1768 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001769 Act->Execute();
1770
1771 // Steal the created target, context, and preprocessor.
1772 AST->TheSema.reset(Clang->takeSema());
1773 AST->Consumer.reset(Clang->takeASTConsumer());
1774 AST->Ctx = &Clang->getASTContext();
1775 AST->PP = &Clang->getPreprocessor();
1776 Clang->setSourceManager(0);
1777 Clang->setFileManager(0);
1778 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001779 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780
1781 Act->EndSourceFile();
1782
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001783 if (OwnAST)
1784 return OwnAST.take();
1785 else
1786 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001787}
1788
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001789bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1790 if (!Invocation)
1791 return true;
1792
1793 // We'll manage file buffers ourselves.
1794 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1795 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001796 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001797
Douglas Gregor1aa27302011-01-27 18:02:58 +00001798 // Save the target features.
1799 TargetFeatures = Invocation->getTargetOpts().Features;
1800
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001801 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001802 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001803 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001804 OverrideMainBuffer
1805 = getMainBufferWithPrecompiledPreamble(*Invocation);
1806 }
1807
Douglas Gregor213f18b2010-10-28 15:44:59 +00001808 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001809 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001810
Ted Kremenek25a11e12011-03-22 01:15:24 +00001811 // Recover resources if we crash before exiting this method.
1812 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1813 MemBufferCleanup(OverrideMainBuffer);
1814
Douglas Gregor213f18b2010-10-28 15:44:59 +00001815 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001816}
1817
Douglas Gregorabc563f2010-07-19 21:46:24 +00001818ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001819 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001820 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001821 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001822 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001823 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001824 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001825 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826 // Create the AST unit.
1827 llvm::OwningPtr<ASTUnit> AST;
1828 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001829 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001830 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001831 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001832 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001833 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001834 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001835 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001836 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001837
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001838 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001839 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1840 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001841 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1842 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001843 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001844
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001845 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001846}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001847
1848ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1849 const char **ArgEnd,
David Blaikied6471f72011-09-25 23:23:43 +00001850 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001851 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001852 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001853 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001854 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001855 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001856 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001857 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001858 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001859 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001860 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001861 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001862 // No diagnostics engine was provided, so create our own diagnostics object
1863 // with the default options.
1864 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001865 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1866 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001867 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001868
Chris Lattner5f9e2722011-07-23 10:55:15 +00001869 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001870
Ted Kremenek4f327862011-03-21 18:40:17 +00001871 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001872
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001873 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001874
Douglas Gregore47be3e2010-11-11 00:39:14 +00001875 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001876 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001877
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001878 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001879 llvm::makeArrayRef(ArgBegin, ArgEnd),
1880 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001881 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001882 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001883 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001884
Douglas Gregor4db64a42010-01-23 00:14:00 +00001885 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001886 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1887 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1888 if (const llvm::MemoryBuffer *
1889 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1890 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1891 } else {
1892 const char *fname = fileOrBuf.get<const char *>();
1893 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1894 }
1895 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001896 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1897 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001898
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001899 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001900 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001901
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001902 // Create the AST unit.
1903 llvm::OwningPtr<ASTUnit> AST;
1904 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001905 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001906 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001907 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001908 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001909 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001910 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001911 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001912 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1914 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001916 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001917 CI = 0; // Zero out now to ease cleanup during crash recovery.
Chandler Carruthba7537f2011-07-14 09:02:10 +00001918 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001919
1920 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001921 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1922 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001923
Chris Lattner39b49bc2010-11-23 08:35:12 +00001924 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001925}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001926
1927bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001928 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001929 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001930
1931 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001932
Douglas Gregor213f18b2010-10-28 15:44:59 +00001933 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001934 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001935
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001936 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001937 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001938 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001939 for (PreprocessorOptions::remapped_file_buffer_iterator
1940 R = PPOpts.remapped_file_buffer_begin(),
1941 REnd = PPOpts.remapped_file_buffer_end();
1942 R != REnd;
1943 ++R) {
1944 delete R->second;
1945 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001946 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001947 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1948 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1949 if (const llvm::MemoryBuffer *
1950 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1951 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1952 memBuf);
1953 } else {
1954 const char *fname = fileOrBuf.get<const char *>();
1955 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1956 fname);
1957 }
1958 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001959
Douglas Gregoreababfb2010-08-04 05:53:38 +00001960 // If we have a preamble file lying around, or if we might try to
1961 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001962 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001963 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001964 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001965
Douglas Gregorabc563f2010-07-19 21:46:24 +00001966 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001967 getDiagnostics().Reset();
1968 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00001969 if (OverrideMainBuffer)
1970 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001971
Douglas Gregor175c4a92010-07-23 23:58:40 +00001972 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001973 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001974
1975 // If we're caching global code-completion results, and the top-level
1976 // declarations have changed, clear out the code-completion cache.
1977 if (!Result && ShouldCacheCodeCompletionResults &&
1978 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1979 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001980
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001981 // We now need to clear out the completion allocator for
1982 // clang_getCursorCompletionString; it'll be recreated if necessary.
1983 CursorCompletionAllocator = 0;
1984
Douglas Gregor175c4a92010-07-23 23:58:40 +00001985 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001986}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001987
Douglas Gregor87c08a52010-08-13 22:48:40 +00001988//----------------------------------------------------------------------------//
1989// Code completion
1990//----------------------------------------------------------------------------//
1991
1992namespace {
1993 /// \brief Code completion consumer that combines the cached code-completion
1994 /// results from an ASTUnit with the code-completion results provided to it,
1995 /// then passes the result on to
1996 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001997 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001998 ASTUnit &AST;
1999 CodeCompleteConsumer &Next;
2000
2001 public:
2002 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00002003 bool IncludeMacros, bool IncludeCodePatterns,
2004 bool IncludeGlobals)
2005 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002006 Next.isOutputBinary()), AST(AST), Next(Next)
2007 {
2008 // Compute the set of contexts in which we will look when we don't have
2009 // any information about the specific context.
2010 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002011 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2012 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2013 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2014 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2015 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2016 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2017 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2018 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2019 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2020 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2021 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2022 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2023 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002024
Douglas Gregor87c08a52010-08-13 22:48:40 +00002025 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002026 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2027 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2028 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002029 }
2030
2031 virtual void ProcessCodeCompleteResults(Sema &S,
2032 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002033 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002034 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002035
2036 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2037 OverloadCandidate *Candidates,
2038 unsigned NumCandidates) {
2039 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2040 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002041
Douglas Gregordae68752011-02-01 22:57:45 +00002042 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002043 return Next.getAllocator();
2044 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002045 };
2046}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002047
Douglas Gregor5f808c22010-08-16 21:18:39 +00002048/// \brief Helper function that computes which global names are hidden by the
2049/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002050static void CalculateHiddenNames(const CodeCompletionContext &Context,
2051 CodeCompletionResult *Results,
2052 unsigned NumResults,
2053 ASTContext &Ctx,
2054 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002055 bool OnlyTagNames = false;
2056 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002057 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002058 case CodeCompletionContext::CCC_TopLevel:
2059 case CodeCompletionContext::CCC_ObjCInterface:
2060 case CodeCompletionContext::CCC_ObjCImplementation:
2061 case CodeCompletionContext::CCC_ObjCIvarList:
2062 case CodeCompletionContext::CCC_ClassStructUnion:
2063 case CodeCompletionContext::CCC_Statement:
2064 case CodeCompletionContext::CCC_Expression:
2065 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002066 case CodeCompletionContext::CCC_DotMemberAccess:
2067 case CodeCompletionContext::CCC_ArrowMemberAccess:
2068 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002069 case CodeCompletionContext::CCC_Namespace:
2070 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002071 case CodeCompletionContext::CCC_Name:
2072 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002073 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002074 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002075 break;
2076
2077 case CodeCompletionContext::CCC_EnumTag:
2078 case CodeCompletionContext::CCC_UnionTag:
2079 case CodeCompletionContext::CCC_ClassOrStructTag:
2080 OnlyTagNames = true;
2081 break;
2082
2083 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002084 case CodeCompletionContext::CCC_MacroName:
2085 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002086 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002087 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002088 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002089 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002090 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002091 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002092 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002093 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2094 case CodeCompletionContext::CCC_ObjCClassMessage:
2095 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002096 // We're looking for nothing, or we're looking for names that cannot
2097 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002098 return;
2099 }
2100
John McCall0a2c5e22010-08-25 06:19:51 +00002101 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002102 for (unsigned I = 0; I != NumResults; ++I) {
2103 if (Results[I].Kind != Result::RK_Declaration)
2104 continue;
2105
2106 unsigned IDNS
2107 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2108
2109 bool Hiding = false;
2110 if (OnlyTagNames)
2111 Hiding = (IDNS & Decl::IDNS_Tag);
2112 else {
2113 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002114 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2115 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002116 if (Ctx.getLangOptions().CPlusPlus)
2117 HiddenIDNS |= Decl::IDNS_Tag;
2118 Hiding = (IDNS & HiddenIDNS);
2119 }
2120
2121 if (!Hiding)
2122 continue;
2123
2124 DeclarationName Name = Results[I].Declaration->getDeclName();
2125 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2126 HiddenNames.insert(Identifier->getName());
2127 else
2128 HiddenNames.insert(Name.getAsString());
2129 }
2130}
2131
2132
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002133void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2134 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002135 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002136 unsigned NumResults) {
2137 // Merge the results we were given with the results we cached.
2138 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002139 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002140 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002141 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002142 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002143 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002144 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002145 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002146 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002147 C = AST.cached_completion_begin(),
2148 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002149 C != CEnd; ++C) {
2150 // If the context we are in matches any of the contexts we are
2151 // interested in, we'll add this result.
2152 if ((C->ShowInContexts & InContexts) == 0)
2153 continue;
2154
2155 // If we haven't added any results previously, do so now.
2156 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002157 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2158 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002159 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2160 AddedResult = true;
2161 }
2162
Douglas Gregor5f808c22010-08-16 21:18:39 +00002163 // Determine whether this global completion result is hidden by a local
2164 // completion result. If so, skip it.
2165 if (C->Kind != CXCursor_MacroDefinition &&
2166 HiddenNames.count(C->Completion->getTypedText()))
2167 continue;
2168
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002169 // Adjust priority based on similar type classes.
2170 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002171 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002172 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002173 if (!Context.getPreferredType().isNull()) {
2174 if (C->Kind == CXCursor_MacroDefinition) {
2175 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002176 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002177 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002178 } else if (C->Type) {
2179 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002180 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002181 Context.getPreferredType().getUnqualifiedType());
2182 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2183 if (ExpectedSTC == C->TypeClass) {
2184 // We know this type is similar; check for an exact match.
2185 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002186 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002187 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002188 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002189 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2190 Priority /= CCF_ExactTypeMatch;
2191 else
2192 Priority /= CCF_SimilarTypeMatch;
2193 }
2194 }
2195 }
2196
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002197 // Adjust the completion string, if required.
2198 if (C->Kind == CXCursor_MacroDefinition &&
2199 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2200 // Create a new code-completion string that just contains the
2201 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002202 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2203 C->Availability);
2204 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002205 CursorKind = CXCursor_NotImplemented;
2206 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002207 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002208 }
2209
Douglas Gregor4125c372010-08-25 18:03:13 +00002210 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002211 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002212 }
2213
2214 // If we did not add any cached completion results, just forward the
2215 // results we were given to the next consumer.
2216 if (!AddedResult) {
2217 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2218 return;
2219 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002220
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002221 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2222 AllResults.size());
2223}
2224
2225
2226
Chris Lattner5f9e2722011-07-23 10:55:15 +00002227void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002228 RemappedFile *RemappedFiles,
2229 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002230 bool IncludeMacros,
2231 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002232 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002233 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002234 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002235 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2236 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002237 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002238 return;
2239
Douglas Gregor213f18b2010-10-28 15:44:59 +00002240 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002241 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002242 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002243
Ted Kremenek4f327862011-03-21 18:40:17 +00002244 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2245 CCInvocation(new CompilerInvocation(*Invocation));
2246
2247 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2248 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002249
Douglas Gregor87c08a52010-08-13 22:48:40 +00002250 FrontendOpts.ShowMacrosInCodeCompletion
2251 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002252 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002253 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2254 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002255 FrontendOpts.CodeCompletionAt.FileName = File;
2256 FrontendOpts.CodeCompletionAt.Line = Line;
2257 FrontendOpts.CodeCompletionAt.Column = Column;
2258
2259 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002260 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002261
Ted Kremenek03201fb2011-03-21 18:40:07 +00002262 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2263
2264 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002265 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2266 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002267
Ted Kremenek4f327862011-03-21 18:40:17 +00002268 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002269 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002270
2271 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002272 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002273 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002274 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002275 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002276 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002277
2278 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002279 Clang->getTargetOpts().Features = TargetFeatures;
2280 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2281 Clang->getTargetOpts()));
2282 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002283 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002284 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002285 }
2286
2287 // Inform the target of the language options.
2288 //
2289 // FIXME: We shouldn't need to do this, the target should be immutable once
2290 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002291 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002292
Ted Kremenek03201fb2011-03-21 18:40:07 +00002293 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002294 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002295 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002296 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002297 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002298 "IR inputs not support here!");
2299
2300
2301 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002302 Clang->setFileManager(&FileMgr);
2303 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002304
2305 // Remap files.
2306 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002307 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002308 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002309 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2310 if (const llvm::MemoryBuffer *
2311 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2312 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2313 OwnedBuffers.push_back(memBuf);
2314 } else {
2315 const char *fname = fileOrBuf.get<const char *>();
2316 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2317 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002318 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002319
Douglas Gregor87c08a52010-08-13 22:48:40 +00002320 // Use the code completion consumer we were given, but adding any cached
2321 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002322 AugmentedCodeCompleteConsumer *AugmentedConsumer
2323 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2324 FrontendOpts.ShowMacrosInCodeCompletion,
2325 FrontendOpts.ShowCodePatternsInCodeCompletion,
2326 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002327 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002328
Douglas Gregordf95a132010-08-09 20:45:32 +00002329 // If we have a precompiled preamble, try to use it. We only allow
2330 // the use of the precompiled preamble if we're if the completion
2331 // point is within the main file, after the end of the precompiled
2332 // preamble.
2333 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002334 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002335 using llvm::sys::FileStatus;
2336 llvm::sys::PathWithStatus CompleteFilePath(File);
2337 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2338 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2339 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002340 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2341 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002342 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002343 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002344 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002345 }
2346
2347 // If the main file has been overridden due to the use of a preamble,
2348 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002349 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002350 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002351 stored_diag_begin(),
2352 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002353 if (OverrideMainBuffer) {
2354 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2355 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2356 PreprocessorOpts.PrecompiledPreambleBytes.second
2357 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002358 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002359 PreprocessorOpts.DisablePCHValidation = true;
2360
Douglas Gregor2283d792010-08-20 00:59:43 +00002361 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002362 } else {
2363 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2364 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002365 }
2366
Douglas Gregordca8ee82011-05-06 16:33:08 +00002367 // Disable the preprocessing record
2368 PreprocessorOpts.DetailedRecord = false;
2369
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002370 llvm::OwningPtr<SyntaxOnlyAction> Act;
2371 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002372 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2373 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002374 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002375 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002376 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2377 getSourceManager(), PreambleDiagnostics,
2378 StoredDiagnostics);
2379 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002380 Act->Execute();
2381 Act->EndSourceFile();
2382 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002383}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002384
Chris Lattner5f9e2722011-07-23 10:55:15 +00002385CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002386 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002387 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002388
2389 // Write to a temporary file and later rename it to the actual file, to avoid
2390 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002391 llvm::SmallString<128> TempPath;
2392 TempPath = File;
2393 TempPath += "-%%%%%%%%";
2394 int fd;
2395 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2396 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002397 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002398
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002399 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2400 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002401 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002402
2403 serialize(Out);
2404 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002405 if (Out.has_error())
2406 return CXSaveError_Unknown;
2407
2408 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2409 bool exists;
2410 llvm::sys::fs::remove(TempPath.str(), exists);
2411 return CXSaveError_Unknown;
2412 }
2413
2414 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002415}
2416
Chris Lattner5f9e2722011-07-23 10:55:15 +00002417bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002418 if (getDiagnostics().hasErrorOccurred())
2419 return true;
2420
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002421 std::vector<unsigned char> Buffer;
2422 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002423 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002424 // FIXME: Handle modules
2425 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002426
2427 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002428 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002429 OS.write((char *)&Buffer.front(), Buffer.size());
2430
2431 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002432}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002433
2434typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2435
2436static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2437 unsigned Raw = L.getRawEncoding();
2438 const unsigned MacroBit = 1U << 31;
2439 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2440 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2441}
2442
2443void ASTUnit::TranslateStoredDiagnostics(
2444 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002445 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002446 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002447 const SmallVectorImpl<StoredDiagnostic> &Diags,
2448 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002449 // The stored diagnostic has the old source manager in it; update
2450 // the locations to refer into the new source manager. We also need to remap
2451 // all the locations to the new view. This includes the diag location, any
2452 // associated source ranges, and the source ranges of associated fix-its.
2453 // FIXME: There should be a cleaner way to do this.
2454
Chris Lattner5f9e2722011-07-23 10:55:15 +00002455 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002456 Result.reserve(Diags.size());
2457 assert(MMan && "Don't have a module manager");
Jonathan D. Turner48d2c3f2011-07-26 18:21:30 +00002458 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002459 assert(Mod && "Don't have preamble module");
2460 SLocRemap &Remap = Mod->SLocRemap;
2461 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2462 // Rebuild the StoredDiagnostic.
2463 const StoredDiagnostic &SD = Diags[I];
2464 SourceLocation L = SD.getLocation();
2465 TranslateSLoc(L, Remap);
2466 FullSourceLoc Loc(L, SrcMgr);
2467
Chris Lattner5f9e2722011-07-23 10:55:15 +00002468 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002469 Ranges.reserve(SD.range_size());
2470 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2471 E = SD.range_end();
2472 I != E; ++I) {
2473 SourceLocation BL = I->getBegin();
2474 TranslateSLoc(BL, Remap);
2475 SourceLocation EL = I->getEnd();
2476 TranslateSLoc(EL, Remap);
2477 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2478 }
2479
Chris Lattner5f9e2722011-07-23 10:55:15 +00002480 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002481 FixIts.reserve(SD.fixit_size());
2482 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2483 E = SD.fixit_end();
2484 I != E; ++I) {
2485 FixIts.push_back(FixItHint());
2486 FixItHint &FH = FixIts.back();
2487 FH.CodeToInsert = I->CodeToInsert;
2488 SourceLocation BL = I->RemoveRange.getBegin();
2489 TranslateSLoc(BL, Remap);
2490 SourceLocation EL = I->RemoveRange.getEnd();
2491 TranslateSLoc(EL, Remap);
2492 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2493 I->RemoveRange.isTokenRange());
2494 }
2495
2496 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2497 SD.getMessage(), Loc, Ranges, FixIts));
2498 }
2499 Result.swap(Out);
2500}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002501
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002502static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2503 std::pair<unsigned, Decl *> R) {
2504 return L.first < R.first;
2505}
2506
2507void ASTUnit::addFileLevelDecl(Decl *D) {
2508 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002509
2510 // We only care about local declarations.
2511 if (D->isFromASTFile())
2512 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002513
2514 SourceManager &SM = *SourceMgr;
2515 SourceLocation Loc = D->getLocation();
2516 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2517 return;
2518
2519 // We only keep track of the file-level declarations of each file.
2520 if (!D->getLexicalDeclContext()->isFileContext())
2521 return;
2522
2523 SourceLocation FileLoc = SM.getFileLoc(Loc);
2524 assert(SM.isLocalSourceLocation(FileLoc));
2525 FileID FID;
2526 unsigned Offset;
2527 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2528 if (FID.isInvalid())
2529 return;
2530
2531 LocDeclsTy *&Decls = FileDecls[FID];
2532 if (!Decls)
2533 Decls = new LocDeclsTy();
2534
2535 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2536
2537 if (Decls->empty() || Decls->back().first <= Offset) {
2538 Decls->push_back(LocDecl);
2539 return;
2540 }
2541
2542 LocDeclsTy::iterator
2543 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2544
2545 Decls->insert(I, LocDecl);
2546}
2547
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002548void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2549 SmallVectorImpl<Decl *> &Decls) {
2550 if (File.isInvalid())
2551 return;
2552
2553 if (SourceMgr->isLoadedFileID(File)) {
2554 assert(Ctx->getExternalSource() && "No external source!");
2555 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2556 Decls);
2557 }
2558
2559 FileDeclsTy::iterator I = FileDecls.find(File);
2560 if (I == FileDecls.end())
2561 return;
2562
2563 LocDeclsTy &LocDecls = *I->second;
2564 if (LocDecls.empty())
2565 return;
2566
2567 LocDeclsTy::iterator
2568 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2569 std::make_pair(Offset, (Decl*)0), compLocDecl);
2570 if (BeginIt != LocDecls.begin())
2571 --BeginIt;
2572
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002573 // If we are pointing at a top-level decl inside an objc container, we need
2574 // to backtrack until we find it otherwise we will fail to report that the
2575 // region overlaps with an objc container.
2576 while (BeginIt != LocDecls.begin() &&
2577 BeginIt->second->isTopLevelDeclInObjCContainer())
2578 --BeginIt;
2579
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002580 LocDeclsTy::iterator
2581 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2582 std::make_pair(Offset+Length, (Decl*)0),
2583 compLocDecl);
2584 if (EndIt != LocDecls.end())
2585 ++EndIt;
2586
2587 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2588 Decls.push_back(DIt->second);
2589}
2590
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002591SourceLocation ASTUnit::getLocation(const FileEntry *File,
2592 unsigned Line, unsigned Col) const {
2593 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002594 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002595 return SM.getMacroArgExpandedLocation(Loc);
2596}
2597
2598SourceLocation ASTUnit::getLocation(const FileEntry *File,
2599 unsigned Offset) const {
2600 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002601 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002602 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2603}
2604
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002605/// \brief If \arg Loc is a loaded location from the preamble, returns
2606/// the corresponding local location of the main file, otherwise it returns
2607/// \arg Loc.
2608SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2609 FileID PreambleID;
2610 if (SourceMgr)
2611 PreambleID = SourceMgr->getPreambleFileID();
2612
2613 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2614 return Loc;
2615
2616 unsigned Offs;
2617 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2618 SourceLocation FileLoc
2619 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2620 return FileLoc.getLocWithOffset(Offs);
2621 }
2622
2623 return Loc;
2624}
2625
2626/// \brief If \arg Loc is a local location of the main file but inside the
2627/// preamble chunk, returns the corresponding loaded location from the
2628/// preamble, otherwise it returns \arg Loc.
2629SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2630 FileID PreambleID;
2631 if (SourceMgr)
2632 PreambleID = SourceMgr->getPreambleFileID();
2633
2634 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2635 return Loc;
2636
2637 unsigned Offs;
2638 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2639 Offs < Preamble.size()) {
2640 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2641 return FileLoc.getLocWithOffset(Offs);
2642 }
2643
2644 return Loc;
2645}
2646
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002647bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2648 FileID FID;
2649 if (SourceMgr)
2650 FID = SourceMgr->getPreambleFileID();
2651
2652 if (Loc.isInvalid() || FID.isInvalid())
2653 return false;
2654
2655 return SourceMgr->isInFileID(Loc, FID);
2656}
2657
2658bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2659 FileID FID;
2660 if (SourceMgr)
2661 FID = SourceMgr->getMainFileID();
2662
2663 if (Loc.isInvalid() || FID.isInvalid())
2664 return false;
2665
2666 return SourceMgr->isInFileID(Loc, FID);
2667}
2668
2669SourceLocation ASTUnit::getEndOfPreambleFileID() {
2670 FileID FID;
2671 if (SourceMgr)
2672 FID = SourceMgr->getPreambleFileID();
2673
2674 if (FID.isInvalid())
2675 return SourceLocation();
2676
2677 return SourceMgr->getLocForEndOfFile(FID);
2678}
2679
2680SourceLocation ASTUnit::getStartOfMainFileID() {
2681 FileID FID;
2682 if (SourceMgr)
2683 FID = SourceMgr->getMainFileID();
2684
2685 if (FID.isInvalid())
2686 return SourceLocation();
2687
2688 return SourceMgr->getLocForStartOfFile(FID);
2689}
2690
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002691void ASTUnit::PreambleData::countLines() const {
2692 NumLines = 0;
2693 if (empty())
2694 return;
2695
2696 for (std::vector<char>::const_iterator
2697 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2698 if (*I == '\n')
2699 ++NumLines;
2700 }
2701 if (Buffer.back() != '\n')
2702 ++NumLines;
2703}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002704
2705#ifndef NDEBUG
2706ASTUnit::ConcurrencyState::ConcurrencyState() {
2707 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2708}
2709
2710ASTUnit::ConcurrencyState::~ConcurrencyState() {
2711 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2712}
2713
2714void ASTUnit::ConcurrencyState::start() {
2715 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2716 assert(acquired && "Concurrent access to ASTUnit!");
2717}
2718
2719void ASTUnit::ConcurrencyState::finish() {
2720 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2721}
2722
2723#else // NDEBUG
2724
2725ASTUnit::ConcurrencyState::ConcurrencyState() {}
2726ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2727void ASTUnit::ConcurrencyState::start() {}
2728void ASTUnit::ConcurrencyState::finish() {}
2729
2730#endif