blob: cc93d46692c38f7c96a1e2c2263afbbc99045a29 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000030#include "clang/Lex/PreprocessorOptions.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000034#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000035#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000037#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000038#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000042#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000043#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000044#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000045#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000046#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000047#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000049#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek1872b312011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
86 /// \brief Temporary files that should be removed when the ASTUnit is
87 /// destroyed.
88 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
89
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Ted Kremenek1872b312011-10-27 17:55:18 +0000106static void cleanupOnDiskMapAtExit(void);
107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
119static void cleanupOnDiskMapAtExit(void) {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
158static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
168 TemporaryFiles[I].eraseFromDisk();
169 TemporaryFiles.clear();
170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::Path(PreambleFile).eraseFromDisk();
175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
193 for (FileDeclsTy::iterator
194 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
195 delete I->second;
196 FileDecls.clear();
197}
198
Ted Kremenek1872b312011-10-27 17:55:18 +0000199void ASTUnit::CleanTemporaryFiles() {
200 getOnDiskData(this).CleanTemporaryFiles();
201}
202
203void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
204 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000205}
206
Douglas Gregoreababfb2010-08-04 05:53:38 +0000207/// \brief After failing to build a precompiled preamble (due to
208/// errors in the source that occurs in the preamble), the number of
209/// reparses during which we'll skip even trying to precompile the
210/// preamble.
211const unsigned DefaultPreambleRebuildInterval = 5;
212
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213/// \brief Tracks the number of ASTUnit objects that are currently active.
214///
215/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000216static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000217
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000218ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000219 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000220 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000221 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000222 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000223 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000224 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000225 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000226 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000227 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000228 CompletionCacheTopLevelHashValue(0),
229 PreambleTopLevelHashValue(0),
230 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000231 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000232 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000233 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
235 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000236}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000237
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000238ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000239 clearFileLevelDecls();
240
Ted Kremenek1872b312011-10-27 17:55:18 +0000241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
243
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
247 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000248 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
250 for (PreprocessorOptions::remapped_file_buffer_iterator
251 FB = PPOpts.remapped_file_buffer_begin(),
252 FBEnd = PPOpts.remapped_file_buffer_end();
253 FB != FBEnd;
254 ++FB)
255 delete FB->second;
256 }
Douglas Gregor28233422010-07-27 14:52:07 +0000257
258 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000259 delete PreambleBuffer;
260
Douglas Gregor213f18b2010-10-28 15:44:59 +0000261 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000262
263 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000264 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000265 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
266 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000267}
268
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000269void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
270
Douglas Gregor8071e422010-08-15 06:18:01 +0000271/// \brief Determine the set of code-completion contexts in which this
272/// declaration should be shown.
273static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
280 if (!ND)
281 return 0;
282
Richard Smith026b3582012-08-14 03:13:00 +0000283 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000294
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000303
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000307
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000312 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000315 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
316 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000318 else
Richard Smith026b3582012-08-14 03:13:00 +0000319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000320
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000323 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000324 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000333 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000337
338 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000339 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 }
341
342 return Contexts;
343}
344
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345void ASTUnit::CacheCodeCompletionResults() {
346 if (!TheSema)
347 return;
348
Douglas Gregor213f18b2010-10-28 15:44:59 +0000349 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000350 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000351
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
354
355 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000356 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000357 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000359 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
360 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361
362 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000363 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
364
Douglas Gregor87c08a52010-08-13 22:48:40 +0000365 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
366 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000368 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000369 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000370 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000371 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000372 getCodeCompletionTUInfo(),
373 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000374 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000375 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000376 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000377 CachedResult.Priority = Results[I].Priority;
378 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000379 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000380
Douglas Gregorf5586f62010-08-16 18:08:11 +0000381 // Keep track of the type of this completion in an ASTContext-agnostic
382 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000383 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000384 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000385 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000386 CachedResult.Type = 0;
387 } else {
388 CanQualType CanUsageType
389 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
390 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
391
392 // Determine whether we have already seen this type. If so, we save
393 // ourselves the work of formatting the type string by using the
394 // temporary, CanQualType-based hash table to find the associated value.
395 unsigned &TypeValue = CompletionTypes[CanUsageType];
396 if (TypeValue == 0) {
397 TypeValue = CompletionTypes.size();
398 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
399 = TypeValue;
400 }
401
402 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000403 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000404
Douglas Gregor8071e422010-08-15 06:18:01 +0000405 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000406
407 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000409 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
410 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000411 uint64_t NNSContexts
412 = (1LL << CodeCompletionContext::CCC_TopLevel)
413 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
414 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
415 | (1LL << CodeCompletionContext::CCC_Statement)
416 | (1LL << CodeCompletionContext::CCC_Expression)
417 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
418 | (1LL << CodeCompletionContext::CCC_EnumTag)
419 | (1LL << CodeCompletionContext::CCC_UnionTag)
420 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
421 | (1LL << CodeCompletionContext::CCC_Type)
422 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
423 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000424
425 if (isa<NamespaceDecl>(Results[I].Declaration) ||
426 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000427 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000428
429 if (unsigned RemainingContexts
430 = NNSContexts & ~CachedResult.ShowInContexts) {
431 // If there any contexts where this completion can be a
432 // nested-name-specifier but isn't already an option, create a
433 // nested-name-specifier completion.
434 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000435 CachedResult.Completion
436 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000437 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000438 getCodeCompletionTUInfo(),
439 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000440 CachedResult.ShowInContexts = RemainingContexts;
441 CachedResult.Priority = CCP_NestedNameSpecifier;
442 CachedResult.TypeClass = STC_Void;
443 CachedResult.Type = 0;
444 CachedCompletionResults.push_back(CachedResult);
445 }
446 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000447 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000448 }
449
Douglas Gregor87c08a52010-08-13 22:48:40 +0000450 case Result::RK_Keyword:
451 case Result::RK_Pattern:
452 // Ignore keywords and patterns; we don't care, since they are so
453 // easily regenerated.
454 break;
455
456 case Result::RK_Macro: {
457 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000458 CachedResult.Completion
459 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000460 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000461 getCodeCompletionTUInfo(),
462 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000463 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000464 = (1LL << CodeCompletionContext::CCC_TopLevel)
465 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
466 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
467 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
468 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
469 | (1LL << CodeCompletionContext::CCC_Statement)
470 | (1LL << CodeCompletionContext::CCC_Expression)
471 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
472 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
473 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
474 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
475 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000476
Douglas Gregor87c08a52010-08-13 22:48:40 +0000477 CachedResult.Priority = Results[I].Priority;
478 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000479 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000480 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000481 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482 CachedCompletionResults.push_back(CachedResult);
483 break;
484 }
485 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000486 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000487
488 // Save the current top-level hash value.
489 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000490}
491
492void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000493 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000494 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000495 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498namespace {
499
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000500/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000502class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000503 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000504 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505 LangOptions &LangOpt;
506 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000516 HeaderSearch &HSI,
517 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000518 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000520 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
521 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor43998902012-10-25 00:09:28 +0000522 Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000523 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000525 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000526 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000527 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000528 return false;
529
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000530 LangOpt = LangOpts;
531 InitializedLanguage = true;
532
533 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000534 return false;
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000537 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000538 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000539 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000540 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 return false;
542
Douglas Gregor57016dd2012-10-16 23:40:58 +0000543 this->TargetOpts = new TargetOptions(TargetOpts);
544 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
545 *this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000546
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000547 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000548 return false;
549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000551 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000552 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 Counter = Value;
557 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000558
559private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000560 void updated() {
561 if (!Target || !InitializedLanguage)
562 return;
563
564 // Inform the target of the language options.
565 //
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
569
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
572
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000575 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000576};
577
David Blaikie26e7a902011-09-26 00:01:39 +0000578class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000580
581public:
David Blaikie26e7a902011-09-26 00:01:39 +0000582 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000584 : StoredDiags(StoredDiags) { }
585
David Blaikied6471f72011-09-25 23:23:43 +0000586 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000587 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000588
589 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
590 // Just drop any diagnostics that come from cloned consumers; they'll
591 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000592 // FIXME: We'd like to be able to capture these somehow, even if it's just
593 // file/line/column, because they could occur when parsing module maps or
594 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000595 return new IgnoringDiagConsumer();
596 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000597};
598
599/// \brief RAII object that optionally captures diagnostics, if
600/// there is no diagnostic client to capture them already.
601class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000602 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000603 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000604 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000605
606public:
David Blaikied6471f72011-09-25 23:23:43 +0000607 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000608 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000609 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000610 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000611 if (RequestCapture || Diags.getClient() == 0) {
612 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000613 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000614 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000615 }
616
617 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000618 if (Diags.getClient() == &Client) {
619 Diags.takeClient();
620 Diags.setClient(PreviousClient);
621 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000622 }
623};
624
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000625} // anonymous namespace
626
David Blaikie26e7a902011-09-26 00:01:39 +0000627void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000628 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000629 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000630 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000631
Douglas Gregora88084b2010-02-18 18:08:43 +0000632 StoredDiags.push_back(StoredDiagnostic(Level, Info));
633}
634
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000635ASTDeserializationListener *ASTUnit::getDeserializationListener() {
636 if (WriterData)
637 return &WriterData->Writer;
638 return 0;
639}
640
Chris Lattner5f9e2722011-07-23 10:55:15 +0000641llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000642 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000643 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000644 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000645}
646
Douglas Gregore47be3e2010-11-11 00:39:14 +0000647/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000648void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000649 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000650 ASTUnit &AST, bool CaptureDiagnostics) {
651 if (!Diags.getPtr()) {
652 // No diagnostics engine was provided, so create our own diagnostics object
653 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000654 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000655 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000656 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000657 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
658 ArgEnd-ArgBegin,
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000659 ArgBegin, Client,
660 /*ShouldOwnClient=*/true,
661 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000662 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000663 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 }
665}
666
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000667ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000668 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000669 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000670 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000671 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000672 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000673 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000674 bool AllowPCHWithCompilerErrors,
675 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000676 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000677
678 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000679 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
680 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000681 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
682 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000683 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000684
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000685 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000686
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000687 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000688 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000689 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000690 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000691 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000692 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000693 AST->getFileManager(),
694 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000695 AST->HSOpts = new HeaderSearchOptions();
696
697 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
698 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000699 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000700 AST->ASTFileLangOpts,
701 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000702
Douglas Gregor4db64a42010-01-23 00:14:00 +0000703 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000704 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
705 if (const llvm::MemoryBuffer *
706 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
707 // Create the file entry for the file that we're mapping from.
708 const FileEntry *FromFile
709 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
710 memBuf->getBufferSize(),
711 0);
712 if (!FromFile) {
713 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
714 << RemappedFiles[I].first;
715 delete memBuf;
716 continue;
717 }
718
719 // Override the contents of the "from" file with the contents of
720 // the "to" file.
721 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
722
723 } else {
724 const char *fname = fileOrBuf.get<const char *>();
725 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
726 if (!ToFile) {
727 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
728 << RemappedFiles[I].first << fname;
729 continue;
730 }
731
732 // Create the file entry for the file that we're mapping from.
733 const FileEntry *FromFile
734 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
735 ToFile->getSize(),
736 0);
737 if (!FromFile) {
738 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
739 << RemappedFiles[I].first;
740 delete memBuf;
741 continue;
742 }
743
744 // Override the contents of the "from" file with the contents of
745 // the "to" file.
746 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000747 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000748 }
749
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000750 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000752 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000753 unsigned Counter;
754
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000755 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000756
Douglas Gregor36a16492012-10-24 17:46:57 +0000757 AST->PP = new Preprocessor(new PreprocessorOptions(),
758 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000759 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
760 *AST,
761 /*IILookup=*/0,
762 /*OwnsHeaderSearch=*/false,
763 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000764 Preprocessor &PP = *AST->PP;
765
766 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
767 AST->getSourceManager(),
768 /*Target=*/0,
769 PP.getIdentifierTable(),
770 PP.getSelectorTable(),
771 PP.getBuiltinInfo(),
772 /* size_reserve = */0,
773 /*DelayInitialization=*/true);
774 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000775
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000776 bool disableValid = false;
777 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
778 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000779 Reader.reset(new ASTReader(PP, Context,
780 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000781 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000782 /*DisableStatCache=*/false,
783 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000784
785 // Recover resources if we crash before exiting this method.
786 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
787 ReaderCleanup(Reader.get());
788
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000789 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000790 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000791 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000792 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000793
Douglas Gregor38295be2012-10-22 23:51:00 +0000794 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
795 ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000796 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000797 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000799 case ASTReader::Failure:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000800 case ASTReader::OutOfDate:
801 case ASTReader::VersionMismatch:
802 case ASTReader::ConfigurationMismatch:
803 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000804 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000805 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000808 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
809
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000810 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000812 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000813 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000814 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000815 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000816 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000817
818 // Unregister the cleanup for ASTReader. It will get cleaned up
819 // by the ASTUnit cleanup.
820 ReaderCleanup.unregister();
821
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000822 Context.setExternalSource(Source);
823
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000824 // Create an AST consumer, even though it isn't used.
825 AST->Consumer.reset(new ASTConsumer);
826
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000827 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000828 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
829 AST->TheSema->Initialize();
830 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000831 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000832
Mike Stump1eb44332009-09-09 15:08:12 +0000833 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000834}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000835
836namespace {
837
Douglas Gregor9b7db622011-02-16 18:16:54 +0000838/// \brief Preprocessor callback class that updates a hash value with the names
839/// of all macros that have been defined by the translation unit.
840class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
841 unsigned &Hash;
842
843public:
844 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
845
846 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
847 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
848 }
849};
850
851/// \brief Add the given declaration to the hash of all top-level entities.
852void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
853 if (!D)
854 return;
855
856 DeclContext *DC = D->getDeclContext();
857 if (!DC)
858 return;
859
860 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
861 return;
862
863 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
864 if (ND->getIdentifier())
865 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
866 else if (DeclarationName Name = ND->getDeclName()) {
867 std::string NameStr = Name.getAsString();
868 Hash = llvm::HashString(NameStr, Hash);
869 }
870 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000871 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000872}
873
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000874class TopLevelDeclTrackerConsumer : public ASTConsumer {
875 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000876 unsigned &Hash;
877
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000878public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000879 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
880 : Unit(_Unit), Hash(Hash) {
881 Hash = 0;
882 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000883
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000884 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000885 if (!D)
886 return;
887
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000888 // FIXME: Currently ObjC method declarations are incorrectly being
889 // reported as top-level declarations, even though their DeclContext
890 // is the containing ObjC @interface/@implementation. This is a
891 // fundamental problem in the parser right now.
892 if (isa<ObjCMethodDecl>(D))
893 return;
894
895 AddTopLevelDeclarationToHash(D, Hash);
896 Unit.addTopLevelDecl(D);
897
898 handleFileLevelDecl(D);
899 }
900
901 void handleFileLevelDecl(Decl *D) {
902 Unit.addFileLevelDecl(D);
903 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
904 for (NamespaceDecl::decl_iterator
905 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
906 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000907 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000908 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000909
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000910 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000911 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
912 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000913 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000914 }
915
Sebastian Redl27372b42010-08-11 18:52:41 +0000916 // We're not interested in "interesting" decls.
917 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000918
919 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
920 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
921 handleTopLevelDecl(*it);
922 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000923
924 virtual ASTDeserializationListener *GetASTDeserializationListener() {
925 return Unit.getDeserializationListener();
926 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000927};
928
929class TopLevelDeclTrackerAction : public ASTFrontendAction {
930public:
931 ASTUnit &Unit;
932
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000933 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000934 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000935 CI.getPreprocessor().addPPCallbacks(
936 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
937 return new TopLevelDeclTrackerConsumer(Unit,
938 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000939 }
940
941public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000942 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
943
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000944 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000945 virtual TranslationUnitKind getTranslationUnitKind() {
946 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000947 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000948};
949
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000950class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000951 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000952 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000953 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000954
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000955public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000956 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000957 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000958 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000959 Hash(Unit.getCurrentTopLevelHashValue()) {
960 Hash = 0;
961 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000962
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000963 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000964 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
965 Decl *D = *it;
966 // FIXME: Currently ObjC method declarations are incorrectly being
967 // reported as top-level declarations, even though their DeclContext
968 // is the containing ObjC @interface/@implementation. This is a
969 // fundamental problem in the parser right now.
970 if (isa<ObjCMethodDecl>(D))
971 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000972 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000973 TopLevelDecls.push_back(D);
974 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000975 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000976 }
977
978 virtual void HandleTranslationUnit(ASTContext &Ctx) {
979 PCHGenerator::HandleTranslationUnit(Ctx);
980 if (!Unit.getDiagnostics().hasErrorOccurred()) {
981 // Translate the top-level declarations we captured during
982 // parsing into declaration IDs in the precompiled
983 // preamble. This will allow us to deserialize those top-level
984 // declarations when requested.
985 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
986 Unit.addTopLevelDeclFromPreamble(
987 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000988 }
989 }
990};
991
992class PrecompilePreambleAction : public ASTFrontendAction {
993 ASTUnit &Unit;
994
995public:
996 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
997
998 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000999 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001000 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001001 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001002 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001003 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1004 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001005 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001006 return 0;
1007
Douglas Gregor832d6202011-07-22 16:35:34 +00001008 if (!CI.getFrontendOpts().RelocatablePCH)
1009 Sysroot.clear();
1010
Douglas Gregor9b7db622011-02-16 18:16:54 +00001011 CI.getPreprocessor().addPPCallbacks(
1012 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001013 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1014 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001015 }
1016
1017 virtual bool hasCodeCompletionSupport() const { return false; }
1018 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001019 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001020};
1021
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001022}
1023
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001024static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1025 StoredDiagnostics) {
1026 // Get rid of stored diagnostics except the ones from the driver which do not
1027 // have a source location.
1028 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1029 if (StoredDiagnostics[I].getLocation().isValid()) {
1030 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1031 --I;
1032 }
1033 }
1034}
1035
1036static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1037 StoredDiagnostics,
1038 SourceManager &SM) {
1039 // The stored diagnostic has the old source manager in it; update
1040 // the locations to refer into the new source manager. Since we've
1041 // been careful to make sure that the source manager's state
1042 // before and after are identical, so that we can reuse the source
1043 // location itself.
1044 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1045 if (StoredDiagnostics[I].getLocation().isValid()) {
1046 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1047 StoredDiagnostics[I].setLocation(Loc);
1048 }
1049 }
1050}
1051
Douglas Gregorabc563f2010-07-19 21:46:24 +00001052/// Parse the source file into a translation unit using the given compiler
1053/// invocation, replacing the current translation unit.
1054///
1055/// \returns True if a failure occurred that causes the ASTUnit not to
1056/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001057bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001058 delete SavedMainFileBuffer;
1059 SavedMainFileBuffer = 0;
1060
Ted Kremenek4f327862011-03-21 18:40:17 +00001061 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001062 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001063 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001064 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001065
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001066 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001067 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001068
1069 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001070 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1071 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001072
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001073 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001074 CCInvocation(new CompilerInvocation(*Invocation));
1075
1076 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001077 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001078
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001079 // Set up diagnostics, capturing any diagnostics that would
1080 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001081 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001082
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001083 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001084 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001085 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001086 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001087 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001089 }
1090
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001091 // Inform the target of the language options.
1092 //
1093 // FIXME: We shouldn't need to do this, the target should be immutable once
1094 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001095 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001096
Ted Kremenek03201fb2011-03-21 18:40:07 +00001097 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001098 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001099 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001100 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001101 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001102 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001103
Douglas Gregorabc563f2010-07-19 21:46:24 +00001104 // Configure the various subsystems.
1105 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001106 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001107 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001108 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001109 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1110 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001111 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001112 Ctx = 0;
1113 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001114 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001115
1116 // Clear out old caches and data.
1117 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001118 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001119 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001120
Douglas Gregorf128fed2010-08-20 00:02:33 +00001121 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001122 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001123 TopLevelDeclsInPreamble.clear();
1124 }
1125
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001126 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001127 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001128
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001129 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001130 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001132 // If the main file has been overridden due to the use of a preamble,
1133 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001134 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001135 if (OverrideMainBuffer) {
1136 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1137 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1138 PreprocessorOpts.PrecompiledPreambleBytes.second
1139 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001140 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001141 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001142
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001143 // The stored diagnostic has the old source manager in it; update
1144 // the locations to refer into the new source manager. Since we've
1145 // been careful to make sure that the source manager's state
1146 // before and after are identical, so that we can reuse the source
1147 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001148 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001149
1150 // Keep track of the override buffer;
1151 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001152 }
1153
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001154 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001155 new TopLevelDeclTrackerAction(*this));
1156
1157 // Recover resources if we crash before exiting this method.
1158 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1159 ActCleanup(Act.get());
1160
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001161 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001162 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001163
1164 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001165 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001166 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1167 getSourceManager(), PreambleDiagnostics,
1168 StoredDiagnostics);
1169 }
1170
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001171 if (!Act->Execute())
1172 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001173
1174 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001175
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001176 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001177
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001178 FailedParseDiagnostics.clear();
1179
Douglas Gregorabc563f2010-07-19 21:46:24 +00001180 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001181
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001182error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001183 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001184 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001185 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001186 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001187 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001188
1189 // Keep the ownership of the data in the ASTUnit because the client may
1190 // want to see the diagnostics.
1191 transferASTDataFromCompilerInstance(*Clang);
1192 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001193 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001194 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001195 return true;
1196}
1197
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198/// \brief Simple function to retrieve a path for a preamble precompiled header.
1199static std::string GetPreamblePCHPath() {
1200 // FIXME: This is lame; sys::Path should provide this function (in particular,
1201 // it should know how to find the temporary files dir).
1202 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001203 // FIXME: This is a hack so that we can override the preamble file during
1204 // crash-recovery testing, which is the only case where the preamble files
1205 // are not necessarily cleaned up.
1206 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1207 if (TmpFile)
1208 return TmpFile;
1209
Douglas Gregor44c181a2010-07-23 00:33:23 +00001210 std::string Error;
1211 const char *TmpDir = ::getenv("TMPDIR");
1212 if (!TmpDir)
1213 TmpDir = ::getenv("TEMP");
1214 if (!TmpDir)
1215 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001216#ifdef LLVM_ON_WIN32
1217 if (!TmpDir)
1218 TmpDir = ::getenv("USERPROFILE");
1219#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 if (!TmpDir)
1221 TmpDir = "/tmp";
1222 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001223 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001225 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001226 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001227 return std::string();
1228
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 return P.str();
1230}
1231
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001232/// \brief Compute the preamble for the main file, providing the source buffer
1233/// that corresponds to the main file along with a pair (bytes, start-of-line)
1234/// that describes the preamble.
1235std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001236ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1237 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001238 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001239 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001240 CreatedBuffer = false;
1241
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 // Try to determine if the main file has been remapped, either from the
1243 // command line (to another file) or directly through the compiler invocation
1244 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001245 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001246 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001247 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1248 // Check whether there is a file-file remapping of the main file
1249 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001250 M = PreprocessorOpts.remapped_file_begin(),
1251 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252 M != E;
1253 ++M) {
1254 llvm::sys::PathWithStatus MPath(M->first);
1255 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1256 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1257 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001258 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001259 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001260 CreatedBuffer = false;
1261 }
1262
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001263 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001264 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001265 return std::make_pair((llvm::MemoryBuffer*)0,
1266 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001267 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 }
1269 }
1270 }
1271
1272 // Check whether there is a file-buffer remapping. It supercedes the
1273 // file-file remapping.
1274 for (PreprocessorOptions::remapped_file_buffer_iterator
1275 M = PreprocessorOpts.remapped_file_buffer_begin(),
1276 E = PreprocessorOpts.remapped_file_buffer_end();
1277 M != E;
1278 ++M) {
1279 llvm::sys::PathWithStatus MPath(M->first);
1280 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1281 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1282 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001284 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 CreatedBuffer = false;
1286 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001287
Douglas Gregor175c4a92010-07-23 23:58:40 +00001288 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001289 }
1290 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001291 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001292 }
1293
1294 // If the main source file was not remapped, load it now.
1295 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001296 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001297 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001298 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001299
1300 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001301 }
1302
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001303 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001304 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001305 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001306}
1307
Douglas Gregor754f3492010-07-24 00:38:13 +00001308static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001309 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001310 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001311 llvm::MemoryBuffer *Result
1312 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1313 memcpy(const_cast<char*>(Result->getBufferStart()),
1314 Old->getBufferStart(), Old->getBufferSize());
1315 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001316 ' ', NewSize - Old->getBufferSize() - 1);
1317 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001318
Douglas Gregor754f3492010-07-24 00:38:13 +00001319 return Result;
1320}
1321
Douglas Gregor175c4a92010-07-23 23:58:40 +00001322/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1323/// the source file.
1324///
1325/// This routine will compute the preamble of the main source file. If a
1326/// non-trivial preamble is found, it will precompile that preamble into a
1327/// precompiled header so that the precompiled preamble can be used to reduce
1328/// reparsing time. If a precompiled preamble has already been constructed,
1329/// this routine will determine if it is still valid and, if so, avoid
1330/// rebuilding the precompiled preamble.
1331///
Douglas Gregordf95a132010-08-09 20:45:32 +00001332/// \param AllowRebuild When true (the default), this routine is
1333/// allowed to rebuild the precompiled preamble if it is found to be
1334/// out-of-date.
1335///
1336/// \param MaxLines When non-zero, the maximum number of lines that
1337/// can occur within the preamble.
1338///
Douglas Gregor754f3492010-07-24 00:38:13 +00001339/// \returns If the precompiled preamble can be used, returns a newly-allocated
1340/// buffer that should be used in place of the main file when doing so.
1341/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001342llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001343 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001344 bool AllowRebuild,
1345 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001346
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001347 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001348 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1349 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001350 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001351 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001352
1353 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001354 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001355 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001356
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001357 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001358 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001359 if (CreatedPreambleBuffer)
1360 OwnedPreambleBuffer.reset(NewPreamble.first);
1361
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001362 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001363 // We couldn't find a preamble in the main source. Clear out the current
1364 // preamble, if we have one. It's obviously no good any more.
1365 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001366 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001367
1368 // The next time we actually see a preamble, precompile it.
1369 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001370 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001371 }
1372
1373 if (!Preamble.empty()) {
1374 // We've previously computed a preamble. Check whether we have the same
1375 // preamble now that we did before, and that there's enough space in
1376 // the main-file buffer within the precompiled preamble to fit the
1377 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001378 if (Preamble.size() == NewPreamble.second.first &&
1379 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001380 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001381 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001382 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001383 // The preamble has not changed. We may be able to re-use the precompiled
1384 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001385
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001386 // Check that none of the files used by the preamble have changed.
1387 bool AnyFileChanged = false;
1388
1389 // First, make a record of those files that have been overridden via
1390 // remapping or unsaved_files.
1391 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1392 for (PreprocessorOptions::remapped_file_iterator
1393 R = PreprocessorOpts.remapped_file_begin(),
1394 REnd = PreprocessorOpts.remapped_file_end();
1395 !AnyFileChanged && R != REnd;
1396 ++R) {
1397 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001398 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001399 // If we can't stat the file we're remapping to, assume that something
1400 // horrible happened.
1401 AnyFileChanged = true;
1402 break;
1403 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001404
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001405 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1406 StatBuf.st_mtime);
1407 }
1408 for (PreprocessorOptions::remapped_file_buffer_iterator
1409 R = PreprocessorOpts.remapped_file_buffer_begin(),
1410 REnd = PreprocessorOpts.remapped_file_buffer_end();
1411 !AnyFileChanged && R != REnd;
1412 ++R) {
1413 // FIXME: Should we actually compare the contents of file->buffer
1414 // remappings?
1415 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1416 0);
1417 }
1418
1419 // Check whether anything has changed.
1420 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1421 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1422 !AnyFileChanged && F != FEnd;
1423 ++F) {
1424 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1425 = OverriddenFiles.find(F->first());
1426 if (Overridden != OverriddenFiles.end()) {
1427 // This file was remapped; check whether the newly-mapped file
1428 // matches up with the previous mapping.
1429 if (Overridden->second != F->second)
1430 AnyFileChanged = true;
1431 continue;
1432 }
1433
1434 // The file was not remapped; check whether it has changed on disk.
1435 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001436 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001437 // If we can't stat the file, assume that something horrible happened.
1438 AnyFileChanged = true;
1439 } else if (StatBuf.st_size != F->second.first ||
1440 StatBuf.st_mtime != F->second.second)
1441 AnyFileChanged = true;
1442 }
1443
1444 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001445 // Okay! We can re-use the precompiled preamble.
1446
1447 // Set the state of the diagnostic object to mimic its state
1448 // after parsing the preamble.
1449 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001450 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001451 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001452 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001453
1454 // Create a version of the main file buffer that is padded to
1455 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001456 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001457 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001458 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001459 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001460 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001461
1462 // If we aren't allowed to rebuild the precompiled preamble, just
1463 // return now.
1464 if (!AllowRebuild)
1465 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001466
Douglas Gregor175c4a92010-07-23 23:58:40 +00001467 // We can't reuse the previously-computed preamble. Build a new one.
1468 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001469 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001470 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001471 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001472 } else if (!AllowRebuild) {
1473 // We aren't allowed to rebuild the precompiled preamble; just
1474 // return now.
1475 return 0;
1476 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001477
1478 // If the preamble rebuild counter > 1, it's because we previously
1479 // failed to build a preamble and we're not yet ready to try
1480 // again. Decrement the counter and return a failure.
1481 if (PreambleRebuildCounter > 1) {
1482 --PreambleRebuildCounter;
1483 return 0;
1484 }
1485
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001486 // Create a temporary file for the precompiled preamble. In rare
1487 // circumstances, this can fail.
1488 std::string PreamblePCHPath = GetPreamblePCHPath();
1489 if (PreamblePCHPath.empty()) {
1490 // Try again next time.
1491 PreambleRebuildCounter = 1;
1492 return 0;
1493 }
1494
Douglas Gregor175c4a92010-07-23 23:58:40 +00001495 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001496 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001497 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001498
1499 // Create a new buffer that stores the preamble. The buffer also contains
1500 // extra space for the original contents of the file (which will be present
1501 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001502 // grows.
1503 PreambleReservedSize = NewPreamble.first->getBufferSize();
1504 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001505 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001506 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001507 PreambleReservedSize *= 2;
1508
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001509 // Save the preamble text for later; we'll need to compare against it for
1510 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001511 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001512 Preamble.assign(FileMgr->getFile(MainFilename),
1513 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001514 NewPreamble.first->getBufferStart()
1515 + NewPreamble.second.first);
1516 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1517
Douglas Gregor671947b2010-08-19 01:33:06 +00001518 delete PreambleBuffer;
1519 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001520 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001521 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001523 NewPreamble.first->getBufferStart(), Preamble.size());
1524 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001525 ' ', PreambleReservedSize - Preamble.size() - 1);
1526 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001527
1528 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001529 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001530 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1531
1532 // Tell the compiler invocation to generate a temporary precompiled header.
1533 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001535 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001536 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1537 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538
1539 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001540 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001541
1542 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001543 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1544 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001545
Douglas Gregor01b6e312011-07-01 18:22:13 +00001546 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001547 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001549 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001550 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001551
1552 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001553 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor57016dd2012-10-16 23:40:58 +00001554 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001555 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001556 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1557 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001558 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001559 PreprocessorOpts.eraseRemappedFile(
1560 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001561 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001562 }
1563
1564 // Inform the target of the language options.
1565 //
1566 // FIXME: We shouldn't need to do this, the target should be immutable once
1567 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001568 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569
Ted Kremenek03201fb2011-03-21 18:40:07 +00001570 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001571 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001572 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001574 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001575 "IR inputs not support here!");
1576
1577 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001578 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001579 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001580 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001581 TopLevelDecls.clear();
1582 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001583
1584 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001585 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001586
1587 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001588 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001589 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001591 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001592 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001593 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001594 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1595 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001596 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001597 PreprocessorOpts.eraseRemappedFile(
1598 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001599 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001600 }
1601
1602 Act->Execute();
1603 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001604
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001605 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001606 // There were errors parsing the preamble, so no precompiled header was
1607 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001608 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001609 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1610 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001611 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001613 PreprocessorOpts.eraseRemappedFile(
1614 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001615 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001616 }
1617
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001618 // Transfer any diagnostics generated when parsing the preamble into the set
1619 // of preamble diagnostics.
1620 PreambleDiagnostics.clear();
1621 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001622 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001623 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001624
Douglas Gregor175c4a92010-07-23 23:58:40 +00001625 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001626 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001627 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001628
1629 // Keep track of all of the files that the source manager knows about,
1630 // so we can verify whether they have changed or not.
1631 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001632 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001633 const llvm::MemoryBuffer *MainFileBuffer
1634 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1635 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1636 FEnd = SourceMgr.fileinfo_end();
1637 F != FEnd;
1638 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001639 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001640 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1641 continue;
1642
1643 FilesInPreamble[File->getName()]
1644 = std::make_pair(F->second->getSize(), File->getModificationTime());
1645 }
1646
Douglas Gregoreababfb2010-08-04 05:53:38 +00001647 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001648 PreprocessorOpts.eraseRemappedFile(
1649 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001650
1651 // If the hash of top-level entities differs from the hash of the top-level
1652 // entities the last time we rebuilt the preamble, clear out the completion
1653 // cache.
1654 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1655 CompletionCacheTopLevelHashValue = 0;
1656 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1657 }
1658
Douglas Gregor754f3492010-07-24 00:38:13 +00001659 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001660 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001661 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001662}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001663
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001664void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1665 std::vector<Decl *> Resolved;
1666 Resolved.reserve(TopLevelDeclsInPreamble.size());
1667 ExternalASTSource &Source = *getASTContext().getExternalSource();
1668 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1669 // Resolve the declaration ID to an actual declaration, possibly
1670 // deserializing the declaration in the process.
1671 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1672 if (D)
1673 Resolved.push_back(D);
1674 }
1675 TopLevelDeclsInPreamble.clear();
1676 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1677}
1678
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001679void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1680 // Steal the created target, context, and preprocessor.
1681 TheSema.reset(CI.takeSema());
1682 Consumer.reset(CI.takeASTConsumer());
1683 Ctx = &CI.getASTContext();
1684 PP = &CI.getPreprocessor();
1685 CI.setSourceManager(0);
1686 CI.setFileManager(0);
1687 Target = &CI.getTarget();
1688 Reader = CI.getModuleManager();
1689}
1690
Chris Lattner5f9e2722011-07-23 10:55:15 +00001691StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001692 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001693}
1694
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001695ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001696 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001697 bool CaptureDiagnostics,
1698 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001699 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001700 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001701 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001702 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001703 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001704 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001705 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001706 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1707 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1708 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001709
1710 return AST.take();
1711}
1712
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001713ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001714 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001715 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001716 ASTUnit *Unit,
1717 bool Persistent,
1718 StringRef ResourceFilesPath,
1719 bool OnlyLocalDecls,
1720 bool CaptureDiagnostics,
1721 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001722 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001723 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001724 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001725 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001726 assert(CI && "A CompilerInvocation is required");
1727
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001728 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001729 ASTUnit *AST = Unit;
1730 if (!AST) {
1731 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001732 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001733 AST = OwnAST.get();
1734 }
1735
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001736 if (!ResourceFilesPath.empty()) {
1737 // Override the resources path.
1738 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1739 }
1740 AST->OnlyLocalDecls = OnlyLocalDecls;
1741 AST->CaptureDiagnostics = CaptureDiagnostics;
1742 if (PrecompilePreamble)
1743 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001744 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001745 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001746 AST->IncludeBriefCommentsInCodeCompletion
1747 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001748
1749 // Recover resources if we crash before exiting this method.
1750 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001751 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001752 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1753 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001754 DiagCleanup(Diags.getPtr());
1755
1756 // We'll manage file buffers ourselves.
1757 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1758 CI->getFrontendOpts().DisableFree = false;
1759 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1760
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001762 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001763
1764 // Recover resources if we crash before exiting this method.
1765 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1766 CICleanup(Clang.get());
1767
1768 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001769 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001770
1771 // Set up diagnostics, capturing any diagnostics that would
1772 // otherwise be dropped.
1773 Clang->setDiagnostics(&AST->getDiagnostics());
1774
1775 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1777 Clang->getTargetOpts()));
1778 if (!Clang->hasTarget())
1779 return 0;
1780
1781 // Inform the target of the language options.
1782 //
1783 // FIXME: We shouldn't need to do this, the target should be immutable once
1784 // created. This complexity should be lifted elsewhere.
1785 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1786
1787 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1788 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001789 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001790 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001791 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001792 "IR inputs not supported here!");
1793
1794 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001795 AST->TheSema.reset();
1796 AST->Ctx = 0;
1797 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001798 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001799
1800 // Create a file manager object to provide access to and cache the filesystem.
1801 Clang->setFileManager(&AST->getFileManager());
1802
1803 // Create the source manager.
1804 Clang->setSourceManager(&AST->getSourceManager());
1805
1806 ASTFrontendAction *Act = Action;
1807
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001808 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001809 if (!Act) {
1810 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1811 Act = TrackerAct.get();
1812 }
1813
1814 // Recover resources if we crash before exiting this method.
1815 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1816 ActCleanup(TrackerAct.get());
1817
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001818 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1819 AST->transferASTDataFromCompilerInstance(*Clang);
1820 if (OwnAST && ErrAST)
1821 ErrAST->swap(OwnAST);
1822
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001823 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001824 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001825
1826 if (Persistent && !TrackerAct) {
1827 Clang->getPreprocessor().addPPCallbacks(
1828 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1829 std::vector<ASTConsumer*> Consumers;
1830 if (Clang->hasASTConsumer())
1831 Consumers.push_back(Clang->takeASTConsumer());
1832 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1833 AST->getCurrentTopLevelHashValue()));
1834 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1835 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001836 if (!Act->Execute()) {
1837 AST->transferASTDataFromCompilerInstance(*Clang);
1838 if (OwnAST && ErrAST)
1839 ErrAST->swap(OwnAST);
1840
1841 return 0;
1842 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001843
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001844 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001845 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001846
1847 Act->EndSourceFile();
1848
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001849 if (OwnAST)
1850 return OwnAST.take();
1851 else
1852 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001853}
1854
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001855bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1856 if (!Invocation)
1857 return true;
1858
1859 // We'll manage file buffers ourselves.
1860 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1861 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001862 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001863
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001864 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001865 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001866 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001867 OverrideMainBuffer
1868 = getMainBufferWithPrecompiledPreamble(*Invocation);
1869 }
1870
Douglas Gregor213f18b2010-10-28 15:44:59 +00001871 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001872 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001873
Ted Kremenek25a11e12011-03-22 01:15:24 +00001874 // Recover resources if we crash before exiting this method.
1875 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1876 MemBufferCleanup(OverrideMainBuffer);
1877
Douglas Gregor213f18b2010-10-28 15:44:59 +00001878 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001879}
1880
Douglas Gregorabc563f2010-07-19 21:46:24 +00001881ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001882 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001883 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001884 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001885 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001886 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001887 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001888 bool IncludeBriefCommentsInCodeCompletion,
1889 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001890 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001891 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001892 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001893 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001895 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001896 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001897 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001898 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001899 AST->IncludeBriefCommentsInCodeCompletion
1900 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001901 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001902 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001903
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001904 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001905 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1906 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001907 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1908 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001909 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001910
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001912}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001913
1914ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1915 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001916 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001917 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001918 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001919 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001920 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001921 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001922 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001923 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001924 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001925 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001926 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001927 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001928 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001929 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001930 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001931 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001932 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001933 // No diagnostics engine was provided, so create our own diagnostics object
1934 // with the default options.
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001935 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
1936 ArgEnd - ArgBegin,
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001937 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001938 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001939
Chris Lattner5f9e2722011-07-23 10:55:15 +00001940 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001941
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001942 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001943
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001944 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001945
Douglas Gregore47be3e2010-11-11 00:39:14 +00001946 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001947 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001948
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001949 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001950 llvm::makeArrayRef(ArgBegin, ArgEnd),
1951 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001952 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001953 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001954 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001955
Douglas Gregor4db64a42010-01-23 00:14:00 +00001956 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001957 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1958 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1959 if (const llvm::MemoryBuffer *
1960 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1961 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1962 } else {
1963 const char *fname = fileOrBuf.get<const char *>();
1964 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1965 }
1966 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001967 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1968 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1969 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001970
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001971 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001972 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001973
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001974 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1975
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001976 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001977 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001978 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001979 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001980 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001981 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001982 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001983 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001984 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001985 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001986 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001987 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001988 AST->IncludeBriefCommentsInCodeCompletion
1989 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001990 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001991 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001992 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001993 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001994 if (ForSerialization)
1995 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00001996 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001997
1998 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001999 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2000 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002001
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002002 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2003 // Some error occurred, if caller wants to examine diagnostics, pass it the
2004 // ASTUnit.
2005 if (ErrAST) {
2006 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2007 ErrAST->swap(AST);
2008 }
2009 return 0;
2010 }
2011
2012 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002013}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002014
2015bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002016 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002017 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002018
2019 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002020
Douglas Gregor213f18b2010-10-28 15:44:59 +00002021 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002022 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002023
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002024 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002025 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002026 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002027 for (PreprocessorOptions::remapped_file_buffer_iterator
2028 R = PPOpts.remapped_file_buffer_begin(),
2029 REnd = PPOpts.remapped_file_buffer_end();
2030 R != REnd;
2031 ++R) {
2032 delete R->second;
2033 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002034 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002035 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2036 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2037 if (const llvm::MemoryBuffer *
2038 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2039 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2040 memBuf);
2041 } else {
2042 const char *fname = fileOrBuf.get<const char *>();
2043 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2044 fname);
2045 }
2046 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002047
Douglas Gregoreababfb2010-08-04 05:53:38 +00002048 // If we have a preamble file lying around, or if we might try to
2049 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002050 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002051 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002052 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002053
Douglas Gregorabc563f2010-07-19 21:46:24 +00002054 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002055 getDiagnostics().Reset();
2056 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002057 if (OverrideMainBuffer)
2058 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002059
Douglas Gregor175c4a92010-07-23 23:58:40 +00002060 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002061 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002062
2063 // If we're caching global code-completion results, and the top-level
2064 // declarations have changed, clear out the code-completion cache.
2065 if (!Result && ShouldCacheCodeCompletionResults &&
2066 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2067 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002068
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002069 // We now need to clear out the completion info related to this translation
2070 // unit; it'll be recreated if necessary.
2071 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002072
Douglas Gregor175c4a92010-07-23 23:58:40 +00002073 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002074}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002075
Douglas Gregor87c08a52010-08-13 22:48:40 +00002076//----------------------------------------------------------------------------//
2077// Code completion
2078//----------------------------------------------------------------------------//
2079
2080namespace {
2081 /// \brief Code completion consumer that combines the cached code-completion
2082 /// results from an ASTUnit with the code-completion results provided to it,
2083 /// then passes the result on to
2084 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002085 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002086 ASTUnit &AST;
2087 CodeCompleteConsumer &Next;
2088
2089 public:
2090 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002091 const CodeCompleteOptions &CodeCompleteOpts)
2092 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2093 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002094 {
2095 // Compute the set of contexts in which we will look when we don't have
2096 // any information about the specific context.
2097 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002098 = (1LL << CodeCompletionContext::CCC_TopLevel)
2099 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2100 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2101 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2102 | (1LL << CodeCompletionContext::CCC_Statement)
2103 | (1LL << CodeCompletionContext::CCC_Expression)
2104 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2105 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2106 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2107 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2108 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2109 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2110 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002111
David Blaikie4e4d0842012-03-11 07:00:24 +00002112 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002113 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2114 | (1LL << CodeCompletionContext::CCC_UnionTag)
2115 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002116 }
2117
2118 virtual void ProcessCodeCompleteResults(Sema &S,
2119 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002120 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002121 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002122
2123 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2124 OverloadCandidate *Candidates,
2125 unsigned NumCandidates) {
2126 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2127 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002128
Douglas Gregordae68752011-02-01 22:57:45 +00002129 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002130 return Next.getAllocator();
2131 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002132
2133 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2134 return Next.getCodeCompletionTUInfo();
2135 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002136 };
2137}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002138
Douglas Gregor5f808c22010-08-16 21:18:39 +00002139/// \brief Helper function that computes which global names are hidden by the
2140/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002141static void CalculateHiddenNames(const CodeCompletionContext &Context,
2142 CodeCompletionResult *Results,
2143 unsigned NumResults,
2144 ASTContext &Ctx,
2145 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002146 bool OnlyTagNames = false;
2147 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002148 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002149 case CodeCompletionContext::CCC_TopLevel:
2150 case CodeCompletionContext::CCC_ObjCInterface:
2151 case CodeCompletionContext::CCC_ObjCImplementation:
2152 case CodeCompletionContext::CCC_ObjCIvarList:
2153 case CodeCompletionContext::CCC_ClassStructUnion:
2154 case CodeCompletionContext::CCC_Statement:
2155 case CodeCompletionContext::CCC_Expression:
2156 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002157 case CodeCompletionContext::CCC_DotMemberAccess:
2158 case CodeCompletionContext::CCC_ArrowMemberAccess:
2159 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002160 case CodeCompletionContext::CCC_Namespace:
2161 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002162 case CodeCompletionContext::CCC_Name:
2163 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002164 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002165 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002166 break;
2167
2168 case CodeCompletionContext::CCC_EnumTag:
2169 case CodeCompletionContext::CCC_UnionTag:
2170 case CodeCompletionContext::CCC_ClassOrStructTag:
2171 OnlyTagNames = true;
2172 break;
2173
2174 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002175 case CodeCompletionContext::CCC_MacroName:
2176 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002177 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002178 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002179 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002180 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002181 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002182 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002183 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002184 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2185 case CodeCompletionContext::CCC_ObjCClassMessage:
2186 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002187 // We're looking for nothing, or we're looking for names that cannot
2188 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002189 return;
2190 }
2191
John McCall0a2c5e22010-08-25 06:19:51 +00002192 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002193 for (unsigned I = 0; I != NumResults; ++I) {
2194 if (Results[I].Kind != Result::RK_Declaration)
2195 continue;
2196
2197 unsigned IDNS
2198 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2199
2200 bool Hiding = false;
2201 if (OnlyTagNames)
2202 Hiding = (IDNS & Decl::IDNS_Tag);
2203 else {
2204 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002205 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2206 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002207 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002208 HiddenIDNS |= Decl::IDNS_Tag;
2209 Hiding = (IDNS & HiddenIDNS);
2210 }
2211
2212 if (!Hiding)
2213 continue;
2214
2215 DeclarationName Name = Results[I].Declaration->getDeclName();
2216 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2217 HiddenNames.insert(Identifier->getName());
2218 else
2219 HiddenNames.insert(Name.getAsString());
2220 }
2221}
2222
2223
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002224void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2225 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002226 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002227 unsigned NumResults) {
2228 // Merge the results we were given with the results we cached.
2229 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002230 uint64_t InContexts =
2231 Context.getKind() == CodeCompletionContext::CCC_Recovery
2232 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002233 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002234 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002235 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002236 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002237 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002238 C = AST.cached_completion_begin(),
2239 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002240 C != CEnd; ++C) {
2241 // If the context we are in matches any of the contexts we are
2242 // interested in, we'll add this result.
2243 if ((C->ShowInContexts & InContexts) == 0)
2244 continue;
2245
2246 // If we haven't added any results previously, do so now.
2247 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002248 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2249 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002250 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2251 AddedResult = true;
2252 }
2253
Douglas Gregor5f808c22010-08-16 21:18:39 +00002254 // Determine whether this global completion result is hidden by a local
2255 // completion result. If so, skip it.
2256 if (C->Kind != CXCursor_MacroDefinition &&
2257 HiddenNames.count(C->Completion->getTypedText()))
2258 continue;
2259
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002260 // Adjust priority based on similar type classes.
2261 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002262 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002263 if (!Context.getPreferredType().isNull()) {
2264 if (C->Kind == CXCursor_MacroDefinition) {
2265 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002266 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002267 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002268 } else if (C->Type) {
2269 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002270 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002271 Context.getPreferredType().getUnqualifiedType());
2272 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2273 if (ExpectedSTC == C->TypeClass) {
2274 // We know this type is similar; check for an exact match.
2275 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002276 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002277 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002278 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002279 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2280 Priority /= CCF_ExactTypeMatch;
2281 else
2282 Priority /= CCF_SimilarTypeMatch;
2283 }
2284 }
2285 }
2286
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002287 // Adjust the completion string, if required.
2288 if (C->Kind == CXCursor_MacroDefinition &&
2289 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2290 // Create a new code-completion string that just contains the
2291 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002292 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2293 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002294 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002295 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002296 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002297 }
2298
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002299 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002300 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 }
2302
2303 // If we did not add any cached completion results, just forward the
2304 // results we were given to the next consumer.
2305 if (!AddedResult) {
2306 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2307 return;
2308 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002309
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002310 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2311 AllResults.size());
2312}
2313
2314
2315
Chris Lattner5f9e2722011-07-23 10:55:15 +00002316void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002317 RemappedFile *RemappedFiles,
2318 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002319 bool IncludeMacros,
2320 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002321 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002322 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002323 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002324 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002325 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2326 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002327 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002328 return;
2329
Douglas Gregor213f18b2010-10-28 15:44:59 +00002330 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002331 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002332 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002333
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002334 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002335 CCInvocation(new CompilerInvocation(*Invocation));
2336
2337 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002338 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002339 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002340
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002341 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2342 CachedCompletionResults.empty();
2343 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2344 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2345 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2346
2347 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2348
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002349 FrontendOpts.CodeCompletionAt.FileName = File;
2350 FrontendOpts.CodeCompletionAt.Line = Line;
2351 FrontendOpts.CodeCompletionAt.Column = Column;
2352
2353 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002354 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002356 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002357
2358 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002359 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2360 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002361
Ted Kremenek4f327862011-03-21 18:40:17 +00002362 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002363 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002364
2365 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002366 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002367 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002369 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002370 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002371
2372 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002373 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2374 Clang->getTargetOpts()));
2375 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002376 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002377 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002378 }
2379
2380 // Inform the target of the language options.
2381 //
2382 // FIXME: We shouldn't need to do this, the target should be immutable once
2383 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002384 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002385
Ted Kremenek03201fb2011-03-21 18:40:07 +00002386 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002387 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002388 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002389 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002390 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002391 "IR inputs not support here!");
2392
2393
2394 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002395 Clang->setFileManager(&FileMgr);
2396 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397
2398 // Remap files.
2399 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002400 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002401 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002402 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2403 if (const llvm::MemoryBuffer *
2404 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2405 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2406 OwnedBuffers.push_back(memBuf);
2407 } else {
2408 const char *fname = fileOrBuf.get<const char *>();
2409 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2410 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002411 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412
Douglas Gregor87c08a52010-08-13 22:48:40 +00002413 // Use the code completion consumer we were given, but adding any cached
2414 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002415 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002416 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418
Douglas Gregordf95a132010-08-09 20:45:32 +00002419 // If we have a precompiled preamble, try to use it. We only allow
2420 // the use of the precompiled preamble if we're if the completion
2421 // point is within the main file, after the end of the precompiled
2422 // preamble.
2423 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002424 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002425 using llvm::sys::FileStatus;
2426 llvm::sys::PathWithStatus CompleteFilePath(File);
2427 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2428 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2429 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002430 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2431 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002432 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002433 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002434 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002435 }
2436
2437 // If the main file has been overridden due to the use of a preamble,
2438 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002439 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002440 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002441 stored_diag_begin(),
2442 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002443 if (OverrideMainBuffer) {
2444 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2445 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2446 PreprocessorOpts.PrecompiledPreambleBytes.second
2447 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002448 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002449 PreprocessorOpts.DisablePCHValidation = true;
2450
Douglas Gregor2283d792010-08-20 00:59:43 +00002451 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002452 } else {
2453 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2454 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002455 }
2456
Douglas Gregordca8ee82011-05-06 16:33:08 +00002457 // Disable the preprocessing record
2458 PreprocessorOpts.DetailedRecord = false;
2459
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002460 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002461 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002462 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002463 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002464 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002465 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2466 getSourceManager(), PreambleDiagnostics,
2467 StoredDiagnostics);
2468 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002469 Act->Execute();
2470 Act->EndSourceFile();
2471 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002472
2473 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002474}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002475
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002476bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002477 // Write to a temporary file and later rename it to the actual file, to avoid
2478 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002479 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002480 TempPath = File;
2481 TempPath += "-%%%%%%%%";
2482 int fd;
2483 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2484 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002485 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002486
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002487 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2488 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002489 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002490
2491 serialize(Out);
2492 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002493 if (Out.has_error()) {
2494 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002495 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002496 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002497
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002498 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002499 bool exists;
2500 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002501 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002502 }
2503
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002504 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002505}
2506
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002507static bool serializeUnit(ASTWriter &Writer,
2508 SmallVectorImpl<char> &Buffer,
2509 Sema &S,
2510 bool hasErrors,
2511 raw_ostream &OS) {
2512 Writer.WriteAST(S, 0, std::string(), 0, "", hasErrors);
2513
2514 // Write the generated bitstream to "Out".
2515 if (!Buffer.empty())
2516 OS.write(Buffer.data(), Buffer.size());
2517
2518 return false;
2519}
2520
Chris Lattner5f9e2722011-07-23 10:55:15 +00002521bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002522 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002523
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002524 if (WriterData)
2525 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2526 getSema(), hasErrors, OS);
2527
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002528 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002529 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002530 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002531 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002532}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002533
2534typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2535
2536static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2537 unsigned Raw = L.getRawEncoding();
2538 const unsigned MacroBit = 1U << 31;
2539 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2540 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2541}
2542
2543void ASTUnit::TranslateStoredDiagnostics(
2544 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002545 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002546 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002547 const SmallVectorImpl<StoredDiagnostic> &Diags,
2548 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002549 // The stored diagnostic has the old source manager in it; update
2550 // the locations to refer into the new source manager. We also need to remap
2551 // all the locations to the new view. This includes the diag location, any
2552 // associated source ranges, and the source ranges of associated fix-its.
2553 // FIXME: There should be a cleaner way to do this.
2554
Chris Lattner5f9e2722011-07-23 10:55:15 +00002555 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002556 Result.reserve(Diags.size());
2557 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002558 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002559 assert(Mod && "Don't have preamble module");
2560 SLocRemap &Remap = Mod->SLocRemap;
2561 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2562 // Rebuild the StoredDiagnostic.
2563 const StoredDiagnostic &SD = Diags[I];
2564 SourceLocation L = SD.getLocation();
2565 TranslateSLoc(L, Remap);
2566 FullSourceLoc Loc(L, SrcMgr);
2567
Chris Lattner5f9e2722011-07-23 10:55:15 +00002568 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002569 Ranges.reserve(SD.range_size());
2570 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2571 E = SD.range_end();
2572 I != E; ++I) {
2573 SourceLocation BL = I->getBegin();
2574 TranslateSLoc(BL, Remap);
2575 SourceLocation EL = I->getEnd();
2576 TranslateSLoc(EL, Remap);
2577 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2578 }
2579
Chris Lattner5f9e2722011-07-23 10:55:15 +00002580 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002581 FixIts.reserve(SD.fixit_size());
2582 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2583 E = SD.fixit_end();
2584 I != E; ++I) {
2585 FixIts.push_back(FixItHint());
2586 FixItHint &FH = FixIts.back();
2587 FH.CodeToInsert = I->CodeToInsert;
2588 SourceLocation BL = I->RemoveRange.getBegin();
2589 TranslateSLoc(BL, Remap);
2590 SourceLocation EL = I->RemoveRange.getEnd();
2591 TranslateSLoc(EL, Remap);
2592 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2593 I->RemoveRange.isTokenRange());
2594 }
2595
2596 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2597 SD.getMessage(), Loc, Ranges, FixIts));
2598 }
2599 Result.swap(Out);
2600}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002601
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002602static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2603 std::pair<unsigned, Decl *> R) {
2604 return L.first < R.first;
2605}
2606
2607void ASTUnit::addFileLevelDecl(Decl *D) {
2608 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002609
2610 // We only care about local declarations.
2611 if (D->isFromASTFile())
2612 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002613
2614 SourceManager &SM = *SourceMgr;
2615 SourceLocation Loc = D->getLocation();
2616 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2617 return;
2618
2619 // We only keep track of the file-level declarations of each file.
2620 if (!D->getLexicalDeclContext()->isFileContext())
2621 return;
2622
2623 SourceLocation FileLoc = SM.getFileLoc(Loc);
2624 assert(SM.isLocalSourceLocation(FileLoc));
2625 FileID FID;
2626 unsigned Offset;
2627 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2628 if (FID.isInvalid())
2629 return;
2630
2631 LocDeclsTy *&Decls = FileDecls[FID];
2632 if (!Decls)
2633 Decls = new LocDeclsTy();
2634
2635 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2636
2637 if (Decls->empty() || Decls->back().first <= Offset) {
2638 Decls->push_back(LocDecl);
2639 return;
2640 }
2641
2642 LocDeclsTy::iterator
2643 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2644
2645 Decls->insert(I, LocDecl);
2646}
2647
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002648void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2649 SmallVectorImpl<Decl *> &Decls) {
2650 if (File.isInvalid())
2651 return;
2652
2653 if (SourceMgr->isLoadedFileID(File)) {
2654 assert(Ctx->getExternalSource() && "No external source!");
2655 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2656 Decls);
2657 }
2658
2659 FileDeclsTy::iterator I = FileDecls.find(File);
2660 if (I == FileDecls.end())
2661 return;
2662
2663 LocDeclsTy &LocDecls = *I->second;
2664 if (LocDecls.empty())
2665 return;
2666
2667 LocDeclsTy::iterator
2668 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2669 std::make_pair(Offset, (Decl*)0), compLocDecl);
2670 if (BeginIt != LocDecls.begin())
2671 --BeginIt;
2672
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002673 // If we are pointing at a top-level decl inside an objc container, we need
2674 // to backtrack until we find it otherwise we will fail to report that the
2675 // region overlaps with an objc container.
2676 while (BeginIt != LocDecls.begin() &&
2677 BeginIt->second->isTopLevelDeclInObjCContainer())
2678 --BeginIt;
2679
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002680 LocDeclsTy::iterator
2681 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2682 std::make_pair(Offset+Length, (Decl*)0),
2683 compLocDecl);
2684 if (EndIt != LocDecls.end())
2685 ++EndIt;
2686
2687 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2688 Decls.push_back(DIt->second);
2689}
2690
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002691SourceLocation ASTUnit::getLocation(const FileEntry *File,
2692 unsigned Line, unsigned Col) const {
2693 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002694 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002695 return SM.getMacroArgExpandedLocation(Loc);
2696}
2697
2698SourceLocation ASTUnit::getLocation(const FileEntry *File,
2699 unsigned Offset) const {
2700 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002701 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002702 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2703}
2704
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002705/// \brief If \arg Loc is a loaded location from the preamble, returns
2706/// the corresponding local location of the main file, otherwise it returns
2707/// \arg Loc.
2708SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2709 FileID PreambleID;
2710 if (SourceMgr)
2711 PreambleID = SourceMgr->getPreambleFileID();
2712
2713 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2714 return Loc;
2715
2716 unsigned Offs;
2717 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2718 SourceLocation FileLoc
2719 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2720 return FileLoc.getLocWithOffset(Offs);
2721 }
2722
2723 return Loc;
2724}
2725
2726/// \brief If \arg Loc is a local location of the main file but inside the
2727/// preamble chunk, returns the corresponding loaded location from the
2728/// preamble, otherwise it returns \arg Loc.
2729SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2730 FileID PreambleID;
2731 if (SourceMgr)
2732 PreambleID = SourceMgr->getPreambleFileID();
2733
2734 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2735 return Loc;
2736
2737 unsigned Offs;
2738 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2739 Offs < Preamble.size()) {
2740 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2741 return FileLoc.getLocWithOffset(Offs);
2742 }
2743
2744 return Loc;
2745}
2746
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002747bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2748 FileID FID;
2749 if (SourceMgr)
2750 FID = SourceMgr->getPreambleFileID();
2751
2752 if (Loc.isInvalid() || FID.isInvalid())
2753 return false;
2754
2755 return SourceMgr->isInFileID(Loc, FID);
2756}
2757
2758bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2759 FileID FID;
2760 if (SourceMgr)
2761 FID = SourceMgr->getMainFileID();
2762
2763 if (Loc.isInvalid() || FID.isInvalid())
2764 return false;
2765
2766 return SourceMgr->isInFileID(Loc, FID);
2767}
2768
2769SourceLocation ASTUnit::getEndOfPreambleFileID() {
2770 FileID FID;
2771 if (SourceMgr)
2772 FID = SourceMgr->getPreambleFileID();
2773
2774 if (FID.isInvalid())
2775 return SourceLocation();
2776
2777 return SourceMgr->getLocForEndOfFile(FID);
2778}
2779
2780SourceLocation ASTUnit::getStartOfMainFileID() {
2781 FileID FID;
2782 if (SourceMgr)
2783 FID = SourceMgr->getMainFileID();
2784
2785 if (FID.isInvalid())
2786 return SourceLocation();
2787
2788 return SourceMgr->getLocForStartOfFile(FID);
2789}
2790
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002791std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2792ASTUnit::getLocalPreprocessingEntities() const {
2793 if (isMainFileAST()) {
2794 serialization::ModuleFile &
2795 Mod = Reader->getModuleManager().getPrimaryModule();
2796 return Reader->getModulePreprocessedEntities(Mod);
2797 }
2798
2799 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2800 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2801
2802 return std::make_pair(PreprocessingRecord::iterator(),
2803 PreprocessingRecord::iterator());
2804}
2805
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002806bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002807 if (isMainFileAST()) {
2808 serialization::ModuleFile &
2809 Mod = Reader->getModuleManager().getPrimaryModule();
2810 ASTReader::ModuleDeclIterator MDI, MDE;
2811 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2812 for (; MDI != MDE; ++MDI) {
2813 if (!Fn(context, *MDI))
2814 return false;
2815 }
2816
2817 return true;
2818 }
2819
2820 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2821 TLEnd = top_level_end();
2822 TL != TLEnd; ++TL) {
2823 if (!Fn(context, *TL))
2824 return false;
2825 }
2826
2827 return true;
2828}
2829
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002830namespace {
2831struct PCHLocatorInfo {
2832 serialization::ModuleFile *Mod;
2833 PCHLocatorInfo() : Mod(0) {}
2834};
2835}
2836
2837static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2838 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2839 switch (M.Kind) {
2840 case serialization::MK_Module:
2841 return true; // skip dependencies.
2842 case serialization::MK_PCH:
2843 Info.Mod = &M;
2844 return true; // found it.
2845 case serialization::MK_Preamble:
2846 return false; // look in dependencies.
2847 case serialization::MK_MainFile:
2848 return false; // look in dependencies.
2849 }
2850
2851 return true;
2852}
2853
2854const FileEntry *ASTUnit::getPCHFile() {
2855 if (!Reader)
2856 return 0;
2857
2858 PCHLocatorInfo Info;
2859 Reader->getModuleManager().visit(PCHLocator, &Info);
2860 if (Info.Mod)
2861 return Info.Mod->File;
2862
2863 return 0;
2864}
2865
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002866bool ASTUnit::isModuleFile() {
2867 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2868}
2869
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002870void ASTUnit::PreambleData::countLines() const {
2871 NumLines = 0;
2872 if (empty())
2873 return;
2874
2875 for (std::vector<char>::const_iterator
2876 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2877 if (*I == '\n')
2878 ++NumLines;
2879 }
2880 if (Buffer.back() != '\n')
2881 ++NumLines;
2882}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002883
2884#ifndef NDEBUG
2885ASTUnit::ConcurrencyState::ConcurrencyState() {
2886 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2887}
2888
2889ASTUnit::ConcurrencyState::~ConcurrencyState() {
2890 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2891}
2892
2893void ASTUnit::ConcurrencyState::start() {
2894 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2895 assert(acquired && "Concurrent access to ASTUnit!");
2896}
2897
2898void ASTUnit::ConcurrencyState::finish() {
2899 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2900}
2901
2902#else // NDEBUG
2903
2904ASTUnit::ConcurrencyState::ConcurrencyState() {}
2905ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2906void ASTUnit::ConcurrencyState::start() {}
2907void ASTUnit::ConcurrencyState::finish() {}
2908
2909#endif