blob: fcc8ea8f8dfc0515b1c355872343762288c6d2e3 [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"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Serialization/ASTReader.h"
33#include "clang/Serialization/ASTWriter.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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include <cstdlib>
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
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
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
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
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
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000159 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.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000273static unsigned getDeclShowContexts(const 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.
Richard Smith80ad52f2013-01-02 11:42:31 +0000313 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000315 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 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 Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000359 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000360 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000361 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000362
363 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000364 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
365
Douglas Gregor87c08a52010-08-13 22:48:40 +0000366 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
367 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000369 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000370 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000371 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000372 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000373 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000374 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000376 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000377 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000378 CachedResult.Priority = Results[I].Priority;
379 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000380 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000381
Douglas Gregorf5586f62010-08-16 18:08:11 +0000382 // Keep track of the type of this completion in an ASTContext-agnostic
383 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000384 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000385 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 CachedResult.Type = 0;
388 } else {
389 CanQualType CanUsageType
390 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
391 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
392
393 // Determine whether we have already seen this type. If so, we save
394 // ourselves the work of formatting the type string by using the
395 // temporary, CanQualType-based hash table to find the associated value.
396 unsigned &TypeValue = CompletionTypes[CanUsageType];
397 if (TypeValue == 0) {
398 TypeValue = CompletionTypes.size();
399 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
400 = TypeValue;
401 }
402
403 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000404 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000405
Douglas Gregor8071e422010-08-15 06:18:01 +0000406 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000407
408 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000410 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
411 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000412 uint64_t NNSContexts
413 = (1LL << CodeCompletionContext::CCC_TopLevel)
414 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
415 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
416 | (1LL << CodeCompletionContext::CCC_Statement)
417 | (1LL << CodeCompletionContext::CCC_Expression)
418 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
419 | (1LL << CodeCompletionContext::CCC_EnumTag)
420 | (1LL << CodeCompletionContext::CCC_UnionTag)
421 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
422 | (1LL << CodeCompletionContext::CCC_Type)
423 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
424 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000425
426 if (isa<NamespaceDecl>(Results[I].Declaration) ||
427 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000428 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000429
430 if (unsigned RemainingContexts
431 = NNSContexts & ~CachedResult.ShowInContexts) {
432 // If there any contexts where this completion can be a
433 // nested-name-specifier but isn't already an option, create a
434 // nested-name-specifier completion.
435 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000436 CachedResult.Completion
437 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000438 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000439 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000440 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000441 CachedResult.ShowInContexts = RemainingContexts;
442 CachedResult.Priority = CCP_NestedNameSpecifier;
443 CachedResult.TypeClass = STC_Void;
444 CachedResult.Type = 0;
445 CachedCompletionResults.push_back(CachedResult);
446 }
447 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000448 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000449 }
450
Douglas Gregor87c08a52010-08-13 22:48:40 +0000451 case Result::RK_Keyword:
452 case Result::RK_Pattern:
453 // Ignore keywords and patterns; we don't care, since they are so
454 // easily regenerated.
455 break;
456
457 case Result::RK_Macro: {
458 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000459 CachedResult.Completion
460 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000461 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000462 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000463 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000464 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000465 = (1LL << CodeCompletionContext::CCC_TopLevel)
466 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
467 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
468 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
469 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
470 | (1LL << CodeCompletionContext::CCC_Statement)
471 | (1LL << CodeCompletionContext::CCC_Expression)
472 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
473 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
474 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
475 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
476 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000477
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 CachedResult.Priority = Results[I].Priority;
479 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000480 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000481 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000482 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedCompletionResults.push_back(CachedResult);
484 break;
485 }
486 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000487 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000488
489 // Save the current top-level hash value.
490 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000491}
492
493void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000494 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000495 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000496 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000497}
498
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499namespace {
500
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000501/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000503class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000504 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000505 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506 LangOptions &LangOpt;
507 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000508 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000509 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000512 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000514 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000516 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000517 HeaderSearch &HSI,
518 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000519 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000521 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
522 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor43998902012-10-25 00:09:28 +0000523 Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000524 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000526 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000527 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000528 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000529 return false;
530
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000531 LangOpt = LangOpts;
532 InitializedLanguage = true;
533
534 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000535 return false;
536 }
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000538 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000539 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000540 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000541 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000542 return false;
543
Douglas Gregor57016dd2012-10-16 23:40:58 +0000544 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000545 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
546 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000547
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000548 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000549 return false;
550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000552 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000553 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000556 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000557 Counter = Value;
558 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000559
560private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000561 void updated() {
562 if (!Target || !InitializedLanguage)
563 return;
564
565 // Inform the target of the language options.
566 //
567 // FIXME: We shouldn't need to do this, the target should be immutable once
568 // created. This complexity should be lifted elsewhere.
569 Target->setForcedLangOptions(LangOpt);
570
571 // Initialize the preprocessor.
572 PP.Initialize(*Target);
573
574 // Initialize the ASTContext
575 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000576 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000577};
578
David Blaikie26e7a902011-09-26 00:01:39 +0000579class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000580 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000581
582public:
David Blaikie26e7a902011-09-26 00:01:39 +0000583 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000585 : StoredDiags(StoredDiags) { }
586
David Blaikied6471f72011-09-25 23:23:43 +0000587 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000588 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000589
590 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
591 // Just drop any diagnostics that come from cloned consumers; they'll
592 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000593 // FIXME: We'd like to be able to capture these somehow, even if it's just
594 // file/line/column, because they could occur when parsing module maps or
595 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000596 return new IgnoringDiagConsumer();
597 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000598};
599
600/// \brief RAII object that optionally captures diagnostics, if
601/// there is no diagnostic client to capture them already.
602class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000603 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000604 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000605 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000606
607public:
David Blaikied6471f72011-09-25 23:23:43 +0000608 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000609 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000610 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000611 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000612 if (RequestCapture || Diags.getClient() == 0) {
613 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000614 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000615 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000616 }
617
618 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000619 if (Diags.getClient() == &Client) {
620 Diags.takeClient();
621 Diags.setClient(PreviousClient);
622 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000623 }
624};
625
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000626} // anonymous namespace
627
David Blaikie26e7a902011-09-26 00:01:39 +0000628void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000629 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000630 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000631 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000632
Douglas Gregora88084b2010-02-18 18:08:43 +0000633 StoredDiags.push_back(StoredDiagnostic(Level, Info));
634}
635
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000636ASTDeserializationListener *ASTUnit::getDeserializationListener() {
637 if (WriterData)
638 return &WriterData->Writer;
639 return 0;
640}
641
Chris Lattner5f9e2722011-07-23 10:55:15 +0000642llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000643 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000644 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000645 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000646}
647
Douglas Gregore47be3e2010-11-11 00:39:14 +0000648/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000649void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000650 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000651 ASTUnit &AST, bool CaptureDiagnostics) {
652 if (!Diags.getPtr()) {
653 // No diagnostics engine was provided, so create our own diagnostics object
654 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000655 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000656 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000657 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000658 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000659 Client,
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000660 /*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 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000783
784 // Recover resources if we crash before exiting this method.
785 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
786 ReaderCleanup(Reader.get());
787
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000788 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000789 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000790 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000791 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000792
Douglas Gregor38295be2012-10-22 23:51:00 +0000793 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000794 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000795 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000796 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000798 case ASTReader::Failure:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000799 case ASTReader::OutOfDate:
800 case ASTReader::VersionMismatch:
801 case ASTReader::ConfigurationMismatch:
802 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000803 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000804 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000807 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
808
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000809 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000811 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000812 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000813 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000814 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000815 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000816
817 // Unregister the cleanup for ASTReader. It will get cleaned up
818 // by the ASTUnit cleanup.
819 ReaderCleanup.unregister();
820
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000821 Context.setExternalSource(Source);
822
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000823 // Create an AST consumer, even though it isn't used.
824 AST->Consumer.reset(new ASTConsumer);
825
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000826 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000827 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
828 AST->TheSema->Initialize();
829 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000830 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000831
Mike Stump1eb44332009-09-09 15:08:12 +0000832 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000833}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000834
835namespace {
836
Douglas Gregor9b7db622011-02-16 18:16:54 +0000837/// \brief Preprocessor callback class that updates a hash value with the names
838/// of all macros that have been defined by the translation unit.
839class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
840 unsigned &Hash;
841
842public:
843 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
844
845 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
846 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
847 }
848};
849
850/// \brief Add the given declaration to the hash of all top-level entities.
851void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
852 if (!D)
853 return;
854
855 DeclContext *DC = D->getDeclContext();
856 if (!DC)
857 return;
858
859 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
860 return;
861
862 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
863 if (ND->getIdentifier())
864 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
865 else if (DeclarationName Name = ND->getDeclName()) {
866 std::string NameStr = Name.getAsString();
867 Hash = llvm::HashString(NameStr, Hash);
868 }
869 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000870 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000871}
872
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000873class TopLevelDeclTrackerConsumer : public ASTConsumer {
874 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000875 unsigned &Hash;
876
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000877public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000878 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
879 : Unit(_Unit), Hash(Hash) {
880 Hash = 0;
881 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000882
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000883 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000884 if (!D)
885 return;
886
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000887 // FIXME: Currently ObjC method declarations are incorrectly being
888 // reported as top-level declarations, even though their DeclContext
889 // is the containing ObjC @interface/@implementation. This is a
890 // fundamental problem in the parser right now.
891 if (isa<ObjCMethodDecl>(D))
892 return;
893
894 AddTopLevelDeclarationToHash(D, Hash);
895 Unit.addTopLevelDecl(D);
896
897 handleFileLevelDecl(D);
898 }
899
900 void handleFileLevelDecl(Decl *D) {
901 Unit.addFileLevelDecl(D);
902 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
903 for (NamespaceDecl::decl_iterator
904 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
905 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000906 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000907 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000908
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000909 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000910 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
911 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000912 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000913 }
914
Sebastian Redl27372b42010-08-11 18:52:41 +0000915 // We're not interested in "interesting" decls.
916 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000917
918 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
919 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
920 handleTopLevelDecl(*it);
921 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000922
923 virtual ASTDeserializationListener *GetASTDeserializationListener() {
924 return Unit.getDeserializationListener();
925 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000926};
927
928class TopLevelDeclTrackerAction : public ASTFrontendAction {
929public:
930 ASTUnit &Unit;
931
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000932 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000933 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000934 CI.getPreprocessor().addPPCallbacks(
935 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
936 return new TopLevelDeclTrackerConsumer(Unit,
937 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000938 }
939
940public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000941 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
942
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000943 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000944 virtual TranslationUnitKind getTranslationUnitKind() {
945 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000946 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000947};
948
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000949class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000950 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000951 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000952 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000953
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000954public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000955 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000956 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000957 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000958 Hash(Unit.getCurrentTopLevelHashValue()) {
959 Hash = 0;
960 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000961
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000962 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000963 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
964 Decl *D = *it;
965 // FIXME: Currently ObjC method declarations are incorrectly being
966 // reported as top-level declarations, even though their DeclContext
967 // is the containing ObjC @interface/@implementation. This is a
968 // fundamental problem in the parser right now.
969 if (isa<ObjCMethodDecl>(D))
970 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000971 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000972 TopLevelDecls.push_back(D);
973 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000974 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000975 }
976
977 virtual void HandleTranslationUnit(ASTContext &Ctx) {
978 PCHGenerator::HandleTranslationUnit(Ctx);
979 if (!Unit.getDiagnostics().hasErrorOccurred()) {
980 // Translate the top-level declarations we captured during
981 // parsing into declaration IDs in the precompiled
982 // preamble. This will allow us to deserialize those top-level
983 // declarations when requested.
984 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
985 Unit.addTopLevelDeclFromPreamble(
986 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000987 }
988 }
989};
990
991class PrecompilePreambleAction : public ASTFrontendAction {
992 ASTUnit &Unit;
993
994public:
995 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
996
997 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000998 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000999 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001000 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001001 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001002 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1003 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001004 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001005 return 0;
1006
Douglas Gregor832d6202011-07-22 16:35:34 +00001007 if (!CI.getFrontendOpts().RelocatablePCH)
1008 Sysroot.clear();
1009
Douglas Gregor9b7db622011-02-16 18:16:54 +00001010 CI.getPreprocessor().addPPCallbacks(
1011 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001012 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1013 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001014 }
1015
1016 virtual bool hasCodeCompletionSupport() const { return false; }
1017 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001018 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001019};
1020
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001021}
1022
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001023static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1024 StoredDiagnostics) {
1025 // Get rid of stored diagnostics except the ones from the driver which do not
1026 // have a source location.
1027 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1028 if (StoredDiagnostics[I].getLocation().isValid()) {
1029 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1030 --I;
1031 }
1032 }
1033}
1034
1035static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1036 StoredDiagnostics,
1037 SourceManager &SM) {
1038 // The stored diagnostic has the old source manager in it; update
1039 // the locations to refer into the new source manager. Since we've
1040 // been careful to make sure that the source manager's state
1041 // before and after are identical, so that we can reuse the source
1042 // location itself.
1043 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1044 if (StoredDiagnostics[I].getLocation().isValid()) {
1045 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1046 StoredDiagnostics[I].setLocation(Loc);
1047 }
1048 }
1049}
1050
Douglas Gregorabc563f2010-07-19 21:46:24 +00001051/// Parse the source file into a translation unit using the given compiler
1052/// invocation, replacing the current translation unit.
1053///
1054/// \returns True if a failure occurred that causes the ASTUnit not to
1055/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001056bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001057 delete SavedMainFileBuffer;
1058 SavedMainFileBuffer = 0;
1059
Ted Kremenek4f327862011-03-21 18:40:17 +00001060 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001061 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001062 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001063 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001064
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001065 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001066 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001067
1068 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001069 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1070 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001071
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001072 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001073 CCInvocation(new CompilerInvocation(*Invocation));
1074
1075 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001076 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001077
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001078 // Set up diagnostics, capturing any diagnostics that would
1079 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001080 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001081
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001082 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001083 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001084 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001085 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001086 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001087 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001088 }
1089
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001090 // Inform the target of the language options.
1091 //
1092 // FIXME: We shouldn't need to do this, the target should be immutable once
1093 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001094 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001095
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001097 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001098 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001099 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001100 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001101 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001102
Douglas Gregorabc563f2010-07-19 21:46:24 +00001103 // Configure the various subsystems.
1104 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001105 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001106 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001107 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001108 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1109 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001110 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001111 Ctx = 0;
1112 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001113 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001114
1115 // Clear out old caches and data.
1116 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001117 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001118 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001119
Douglas Gregorf128fed2010-08-20 00:02:33 +00001120 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001121 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001122 TopLevelDeclsInPreamble.clear();
1123 }
1124
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001125 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001126 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001127
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001128 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001129 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001130
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001131 // If the main file has been overridden due to the use of a preamble,
1132 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001133 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001134 if (OverrideMainBuffer) {
1135 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1136 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1137 PreprocessorOpts.PrecompiledPreambleBytes.second
1138 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001139 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001140 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001141
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001142 // The stored diagnostic has the old source manager in it; update
1143 // the locations to refer into the new source manager. Since we've
1144 // been careful to make sure that the source manager's state
1145 // before and after are identical, so that we can reuse the source
1146 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001147 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001148
1149 // Keep track of the override buffer;
1150 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 }
1152
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001153 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001154 new TopLevelDeclTrackerAction(*this));
1155
1156 // Recover resources if we crash before exiting this method.
1157 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1158 ActCleanup(Act.get());
1159
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001160 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001161 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001162
1163 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001164 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001165 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1166 getSourceManager(), PreambleDiagnostics,
1167 StoredDiagnostics);
1168 }
1169
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001170 if (!Act->Execute())
1171 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001172
1173 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001174
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001175 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001176
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001177 FailedParseDiagnostics.clear();
1178
Douglas Gregorabc563f2010-07-19 21:46:24 +00001179 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001180
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001181error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001182 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001183 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001184 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001185 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001186 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001187
1188 // Keep the ownership of the data in the ASTUnit because the client may
1189 // want to see the diagnostics.
1190 transferASTDataFromCompilerInstance(*Clang);
1191 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001192 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001193 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001194 return true;
1195}
1196
Douglas Gregor44c181a2010-07-23 00:33:23 +00001197/// \brief Simple function to retrieve a path for a preamble precompiled header.
1198static std::string GetPreamblePCHPath() {
1199 // FIXME: This is lame; sys::Path should provide this function (in particular,
1200 // it should know how to find the temporary files dir).
1201 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001202 // FIXME: This is a hack so that we can override the preamble file during
1203 // crash-recovery testing, which is the only case where the preamble files
1204 // are not necessarily cleaned up.
1205 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1206 if (TmpFile)
1207 return TmpFile;
1208
Douglas Gregor44c181a2010-07-23 00:33:23 +00001209 std::string Error;
1210 const char *TmpDir = ::getenv("TMPDIR");
1211 if (!TmpDir)
1212 TmpDir = ::getenv("TEMP");
1213 if (!TmpDir)
1214 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001215#ifdef LLVM_ON_WIN32
1216 if (!TmpDir)
1217 TmpDir = ::getenv("USERPROFILE");
1218#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 if (!TmpDir)
1220 TmpDir = "/tmp";
1221 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001222 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001223 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001224 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001225 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 return std::string();
1227
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 return P.str();
1229}
1230
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001231/// \brief Compute the preamble for the main file, providing the source buffer
1232/// that corresponds to the main file along with a pair (bytes, start-of-line)
1233/// that describes the preamble.
1234std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001235ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1236 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001237 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001238 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001239 CreatedBuffer = false;
1240
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 // Try to determine if the main file has been remapped, either from the
1242 // command line (to another file) or directly through the compiler invocation
1243 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001244 llvm::MemoryBuffer *Buffer = 0;
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001245 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1247 // Check whether there is a file-file remapping of the main file
1248 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 M = PreprocessorOpts.remapped_file_begin(),
1250 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 M != E;
1252 ++M) {
1253 llvm::sys::PathWithStatus MPath(M->first);
1254 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1255 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1256 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001257 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 CreatedBuffer = false;
1260 }
1261
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001262 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001264 return std::make_pair((llvm::MemoryBuffer*)0,
1265 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001266 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001267 }
1268 }
1269 }
1270
1271 // Check whether there is a file-buffer remapping. It supercedes the
1272 // file-file remapping.
1273 for (PreprocessorOptions::remapped_file_buffer_iterator
1274 M = PreprocessorOpts.remapped_file_buffer_begin(),
1275 E = PreprocessorOpts.remapped_file_buffer_end();
1276 M != E;
1277 ++M) {
1278 llvm::sys::PathWithStatus MPath(M->first);
1279 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1280 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1281 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001282 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001284 CreatedBuffer = false;
1285 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286
Douglas Gregor175c4a92010-07-23 23:58:40 +00001287 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001288 }
1289 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001290 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001291 }
1292
1293 // If the main source file was not remapped, load it now.
1294 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001295 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001296 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001297 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001298
1299 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001300 }
1301
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001302 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001303 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001304 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001305}
1306
Douglas Gregor754f3492010-07-24 00:38:13 +00001307static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001308 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001309 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001310 llvm::MemoryBuffer *Result
1311 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1312 memcpy(const_cast<char*>(Result->getBufferStart()),
1313 Old->getBufferStart(), Old->getBufferSize());
1314 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001315 ' ', NewSize - Old->getBufferSize() - 1);
1316 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001317
Douglas Gregor754f3492010-07-24 00:38:13 +00001318 return Result;
1319}
1320
Douglas Gregor175c4a92010-07-23 23:58:40 +00001321/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1322/// the source file.
1323///
1324/// This routine will compute the preamble of the main source file. If a
1325/// non-trivial preamble is found, it will precompile that preamble into a
1326/// precompiled header so that the precompiled preamble can be used to reduce
1327/// reparsing time. If a precompiled preamble has already been constructed,
1328/// this routine will determine if it is still valid and, if so, avoid
1329/// rebuilding the precompiled preamble.
1330///
Douglas Gregordf95a132010-08-09 20:45:32 +00001331/// \param AllowRebuild When true (the default), this routine is
1332/// allowed to rebuild the precompiled preamble if it is found to be
1333/// out-of-date.
1334///
1335/// \param MaxLines When non-zero, the maximum number of lines that
1336/// can occur within the preamble.
1337///
Douglas Gregor754f3492010-07-24 00:38:13 +00001338/// \returns If the precompiled preamble can be used, returns a newly-allocated
1339/// buffer that should be used in place of the main file when doing so.
1340/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001341llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001342 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001343 bool AllowRebuild,
1344 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001345
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001346 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001347 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1348 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001349 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001350 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001351
1352 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001353 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001354 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001355
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001356 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001357 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001358 if (CreatedPreambleBuffer)
1359 OwnedPreambleBuffer.reset(NewPreamble.first);
1360
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001361 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001362 // We couldn't find a preamble in the main source. Clear out the current
1363 // preamble, if we have one. It's obviously no good any more.
1364 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001365 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001366
1367 // The next time we actually see a preamble, precompile it.
1368 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001369 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001370 }
1371
1372 if (!Preamble.empty()) {
1373 // We've previously computed a preamble. Check whether we have the same
1374 // preamble now that we did before, and that there's enough space in
1375 // the main-file buffer within the precompiled preamble to fit the
1376 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001377 if (Preamble.size() == NewPreamble.second.first &&
1378 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001379 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001380 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001381 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001382 // The preamble has not changed. We may be able to re-use the precompiled
1383 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001384
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001385 // Check that none of the files used by the preamble have changed.
1386 bool AnyFileChanged = false;
1387
1388 // First, make a record of those files that have been overridden via
1389 // remapping or unsaved_files.
1390 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1391 for (PreprocessorOptions::remapped_file_iterator
1392 R = PreprocessorOpts.remapped_file_begin(),
1393 REnd = PreprocessorOpts.remapped_file_end();
1394 !AnyFileChanged && R != REnd;
1395 ++R) {
1396 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001397 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001398 // If we can't stat the file we're remapping to, assume that something
1399 // horrible happened.
1400 AnyFileChanged = true;
1401 break;
1402 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001403
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001404 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1405 StatBuf.st_mtime);
1406 }
1407 for (PreprocessorOptions::remapped_file_buffer_iterator
1408 R = PreprocessorOpts.remapped_file_buffer_begin(),
1409 REnd = PreprocessorOpts.remapped_file_buffer_end();
1410 !AnyFileChanged && R != REnd;
1411 ++R) {
1412 // FIXME: Should we actually compare the contents of file->buffer
1413 // remappings?
1414 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1415 0);
1416 }
1417
1418 // Check whether anything has changed.
1419 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1420 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1421 !AnyFileChanged && F != FEnd;
1422 ++F) {
1423 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1424 = OverriddenFiles.find(F->first());
1425 if (Overridden != OverriddenFiles.end()) {
1426 // This file was remapped; check whether the newly-mapped file
1427 // matches up with the previous mapping.
1428 if (Overridden->second != F->second)
1429 AnyFileChanged = true;
1430 continue;
1431 }
1432
1433 // The file was not remapped; check whether it has changed on disk.
1434 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001435 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001436 // If we can't stat the file, assume that something horrible happened.
1437 AnyFileChanged = true;
1438 } else if (StatBuf.st_size != F->second.first ||
1439 StatBuf.st_mtime != F->second.second)
1440 AnyFileChanged = true;
1441 }
1442
1443 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001444 // Okay! We can re-use the precompiled preamble.
1445
1446 // Set the state of the diagnostic object to mimic its state
1447 // after parsing the preamble.
1448 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001449 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001450 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001451 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001452
1453 // Create a version of the main file buffer that is padded to
1454 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001455 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001456 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001457 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001458 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001459 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001460
1461 // If we aren't allowed to rebuild the precompiled preamble, just
1462 // return now.
1463 if (!AllowRebuild)
1464 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001465
Douglas Gregor175c4a92010-07-23 23:58:40 +00001466 // We can't reuse the previously-computed preamble. Build a new one.
1467 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001468 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001469 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001470 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001471 } else if (!AllowRebuild) {
1472 // We aren't allowed to rebuild the precompiled preamble; just
1473 // return now.
1474 return 0;
1475 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001476
1477 // If the preamble rebuild counter > 1, it's because we previously
1478 // failed to build a preamble and we're not yet ready to try
1479 // again. Decrement the counter and return a failure.
1480 if (PreambleRebuildCounter > 1) {
1481 --PreambleRebuildCounter;
1482 return 0;
1483 }
1484
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001485 // Create a temporary file for the precompiled preamble. In rare
1486 // circumstances, this can fail.
1487 std::string PreamblePCHPath = GetPreamblePCHPath();
1488 if (PreamblePCHPath.empty()) {
1489 // Try again next time.
1490 PreambleRebuildCounter = 1;
1491 return 0;
1492 }
1493
Douglas Gregor175c4a92010-07-23 23:58:40 +00001494 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001495 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001496 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001497
1498 // Create a new buffer that stores the preamble. The buffer also contains
1499 // extra space for the original contents of the file (which will be present
1500 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001501 // grows.
1502 PreambleReservedSize = NewPreamble.first->getBufferSize();
1503 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001504 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001505 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001506 PreambleReservedSize *= 2;
1507
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001508 // Save the preamble text for later; we'll need to compare against it for
1509 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001510 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001511 Preamble.assign(FileMgr->getFile(MainFilename),
1512 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001513 NewPreamble.first->getBufferStart()
1514 + NewPreamble.second.first);
1515 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1516
Douglas Gregor671947b2010-08-19 01:33:06 +00001517 delete PreambleBuffer;
1518 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001519 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001520 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001521 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001522 NewPreamble.first->getBufferStart(), Preamble.size());
1523 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001524 ' ', PreambleReservedSize - Preamble.size() - 1);
1525 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526
1527 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001528 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001529 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1530
1531 // Tell the compiler invocation to generate a temporary precompiled header.
1532 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001534 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001535 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1536 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537
1538 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001539 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001540
1541 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001542 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1543 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001544
Douglas Gregor01b6e312011-07-01 18:22:13 +00001545 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001546 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001547
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001548 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001549 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001550
1551 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001552 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001553 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001555 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1556 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001557 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001558 PreprocessorOpts.eraseRemappedFile(
1559 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001560 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001561 }
1562
1563 // Inform the target of the language options.
1564 //
1565 // FIXME: We shouldn't need to do this, the target should be immutable once
1566 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001567 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001570 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001571 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001572 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001573 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001574 "IR inputs not support here!");
1575
1576 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001577 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001578 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001579 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001580 TopLevelDecls.clear();
1581 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001582
1583 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001584 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001585
1586 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001587 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001588 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001589
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001590 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001591 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001592 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001593 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1594 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001595 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001596 PreprocessorOpts.eraseRemappedFile(
1597 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001598 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001599 }
1600
1601 Act->Execute();
1602 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001603
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001604 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001605 // There were errors parsing the preamble, so no precompiled header was
1606 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001607 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001608 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1609 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001610 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001611 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001612 PreprocessorOpts.eraseRemappedFile(
1613 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001614 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001615 }
1616
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001617 // Transfer any diagnostics generated when parsing the preamble into the set
1618 // of preamble diagnostics.
1619 PreambleDiagnostics.clear();
1620 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001621 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001622 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001623
Douglas Gregor175c4a92010-07-23 23:58:40 +00001624 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001625 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001626 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001627
1628 // Keep track of all of the files that the source manager knows about,
1629 // so we can verify whether they have changed or not.
1630 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001631 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001632 const llvm::MemoryBuffer *MainFileBuffer
1633 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1634 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1635 FEnd = SourceMgr.fileinfo_end();
1636 F != FEnd;
1637 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001638 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001639 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1640 continue;
1641
1642 FilesInPreamble[File->getName()]
1643 = std::make_pair(F->second->getSize(), File->getModificationTime());
1644 }
1645
Douglas Gregoreababfb2010-08-04 05:53:38 +00001646 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001647 PreprocessorOpts.eraseRemappedFile(
1648 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001649
1650 // If the hash of top-level entities differs from the hash of the top-level
1651 // entities the last time we rebuilt the preamble, clear out the completion
1652 // cache.
1653 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1654 CompletionCacheTopLevelHashValue = 0;
1655 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1656 }
1657
Douglas Gregor754f3492010-07-24 00:38:13 +00001658 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001659 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001660 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001661}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001662
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001663void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1664 std::vector<Decl *> Resolved;
1665 Resolved.reserve(TopLevelDeclsInPreamble.size());
1666 ExternalASTSource &Source = *getASTContext().getExternalSource();
1667 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1668 // Resolve the declaration ID to an actual declaration, possibly
1669 // deserializing the declaration in the process.
1670 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1671 if (D)
1672 Resolved.push_back(D);
1673 }
1674 TopLevelDeclsInPreamble.clear();
1675 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1676}
1677
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001678void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1679 // Steal the created target, context, and preprocessor.
1680 TheSema.reset(CI.takeSema());
1681 Consumer.reset(CI.takeASTConsumer());
1682 Ctx = &CI.getASTContext();
1683 PP = &CI.getPreprocessor();
1684 CI.setSourceManager(0);
1685 CI.setFileManager(0);
1686 Target = &CI.getTarget();
1687 Reader = CI.getModuleManager();
1688}
1689
Chris Lattner5f9e2722011-07-23 10:55:15 +00001690StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001691 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1692 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1693 if (Input.isFile())
1694 return Input.getFile();
1695 else
1696 return Input.getBuffer()->getBufferIdentifier();
1697 }
1698
1699 if (SourceMgr) {
1700 if (const FileEntry *
1701 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1702 return FE->getName();
1703 }
1704
1705 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001706}
1707
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001708ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001709 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001710 bool CaptureDiagnostics,
1711 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001712 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001713 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001714 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001715 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001716 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001717 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001718 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001719 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1720 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1721 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001722
1723 return AST.take();
1724}
1725
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001726ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001727 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001728 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001729 ASTUnit *Unit,
1730 bool Persistent,
1731 StringRef ResourceFilesPath,
1732 bool OnlyLocalDecls,
1733 bool CaptureDiagnostics,
1734 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001735 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001736 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001737 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001738 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001739 assert(CI && "A CompilerInvocation is required");
1740
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001741 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001742 ASTUnit *AST = Unit;
1743 if (!AST) {
1744 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001745 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001746 AST = OwnAST.get();
1747 }
1748
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001749 if (!ResourceFilesPath.empty()) {
1750 // Override the resources path.
1751 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1752 }
1753 AST->OnlyLocalDecls = OnlyLocalDecls;
1754 AST->CaptureDiagnostics = CaptureDiagnostics;
1755 if (PrecompilePreamble)
1756 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001757 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001758 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001759 AST->IncludeBriefCommentsInCodeCompletion
1760 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761
1762 // Recover resources if we crash before exiting this method.
1763 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001764 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001765 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1766 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001767 DiagCleanup(Diags.getPtr());
1768
1769 // We'll manage file buffers ourselves.
1770 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1771 CI->getFrontendOpts().DisableFree = false;
1772 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1773
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001774 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001775 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776
1777 // Recover resources if we crash before exiting this method.
1778 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1779 CICleanup(Clang.get());
1780
1781 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001782 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001783
1784 // Set up diagnostics, capturing any diagnostics that would
1785 // otherwise be dropped.
1786 Clang->setDiagnostics(&AST->getDiagnostics());
1787
1788 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001790 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001791 if (!Clang->hasTarget())
1792 return 0;
1793
1794 // Inform the target of the language options.
1795 //
1796 // FIXME: We shouldn't need to do this, the target should be immutable once
1797 // created. This complexity should be lifted elsewhere.
1798 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1799
1800 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1801 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001802 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001803 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001804 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001805 "IR inputs not supported here!");
1806
1807 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001808 AST->TheSema.reset();
1809 AST->Ctx = 0;
1810 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001811 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001812
1813 // Create a file manager object to provide access to and cache the filesystem.
1814 Clang->setFileManager(&AST->getFileManager());
1815
1816 // Create the source manager.
1817 Clang->setSourceManager(&AST->getSourceManager());
1818
1819 ASTFrontendAction *Act = Action;
1820
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001821 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822 if (!Act) {
1823 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1824 Act = TrackerAct.get();
1825 }
1826
1827 // Recover resources if we crash before exiting this method.
1828 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1829 ActCleanup(TrackerAct.get());
1830
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001831 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1832 AST->transferASTDataFromCompilerInstance(*Clang);
1833 if (OwnAST && ErrAST)
1834 ErrAST->swap(OwnAST);
1835
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001836 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001837 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001838
1839 if (Persistent && !TrackerAct) {
1840 Clang->getPreprocessor().addPPCallbacks(
1841 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1842 std::vector<ASTConsumer*> Consumers;
1843 if (Clang->hasASTConsumer())
1844 Consumers.push_back(Clang->takeASTConsumer());
1845 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1846 AST->getCurrentTopLevelHashValue()));
1847 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1848 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001849 if (!Act->Execute()) {
1850 AST->transferASTDataFromCompilerInstance(*Clang);
1851 if (OwnAST && ErrAST)
1852 ErrAST->swap(OwnAST);
1853
1854 return 0;
1855 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001856
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001857 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001858 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001859
1860 Act->EndSourceFile();
1861
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001862 if (OwnAST)
1863 return OwnAST.take();
1864 else
1865 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001866}
1867
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001868bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1869 if (!Invocation)
1870 return true;
1871
1872 // We'll manage file buffers ourselves.
1873 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1874 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001875 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001876
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001877 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001878 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001879 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001880 OverrideMainBuffer
1881 = getMainBufferWithPrecompiledPreamble(*Invocation);
1882 }
1883
Douglas Gregor213f18b2010-10-28 15:44:59 +00001884 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001885 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001886
Ted Kremenek25a11e12011-03-22 01:15:24 +00001887 // Recover resources if we crash before exiting this method.
1888 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1889 MemBufferCleanup(OverrideMainBuffer);
1890
Douglas Gregor213f18b2010-10-28 15:44:59 +00001891 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001892}
1893
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001895 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001896 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001897 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001898 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001899 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001900 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001901 bool IncludeBriefCommentsInCodeCompletion,
1902 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001903 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001904 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001905 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001906 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001907 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001908 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001909 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001910 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001911 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001912 AST->IncludeBriefCommentsInCodeCompletion
1913 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001914 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001915 AST->FileSystemOpts = CI->getFileSystemOpts();
1916 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001917 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001918
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001919 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001920 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1921 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001922 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1923 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001924 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001925
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001926 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001927}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001928
1929ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1930 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001931 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001932 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001933 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001934 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001935 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001936 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001937 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001938 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001939 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001940 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001941 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001942 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001943 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001944 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001945 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001946 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001947 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001948 // No diagnostics engine was provided, so create our own diagnostics object
1949 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001950 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001951 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001952
Chris Lattner5f9e2722011-07-23 10:55:15 +00001953 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001954
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001955 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001956
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001957 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001958
Douglas Gregore47be3e2010-11-11 00:39:14 +00001959 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001960 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001961
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001962 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001963 llvm::makeArrayRef(ArgBegin, ArgEnd),
1964 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001965 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001966 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001967 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001968
Douglas Gregor4db64a42010-01-23 00:14:00 +00001969 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001970 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1971 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1972 if (const llvm::MemoryBuffer *
1973 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1974 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1975 } else {
1976 const char *fname = fileOrBuf.get<const char *>();
1977 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1978 }
1979 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001980 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1981 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1982 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001983
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001984 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001985 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001986
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001987 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1988
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001989 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001990 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001991 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001992 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001993 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001994 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001995 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001996 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001997 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001998 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001999 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002000 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002001 AST->IncludeBriefCommentsInCodeCompletion
2002 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002003 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002004 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002005 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002006 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002007 if (ForSerialization)
2008 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002009 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002010
2011 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002012 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2013 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002014
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002015 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2016 // Some error occurred, if caller wants to examine diagnostics, pass it the
2017 // ASTUnit.
2018 if (ErrAST) {
2019 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2020 ErrAST->swap(AST);
2021 }
2022 return 0;
2023 }
2024
2025 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002026}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002027
2028bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002029 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002030 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002031
2032 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002033
Douglas Gregor213f18b2010-10-28 15:44:59 +00002034 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002035 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002036
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002037 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002038 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2039 for (PreprocessorOptions::remapped_file_buffer_iterator
2040 R = PPOpts.remapped_file_buffer_begin(),
2041 REnd = PPOpts.remapped_file_buffer_end();
2042 R != REnd;
2043 ++R) {
2044 delete R->second;
2045 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002046 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002047 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2048 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2049 if (const llvm::MemoryBuffer *
2050 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2051 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2052 memBuf);
2053 } else {
2054 const char *fname = fileOrBuf.get<const char *>();
2055 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2056 fname);
2057 }
2058 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002059
Douglas Gregoreababfb2010-08-04 05:53:38 +00002060 // If we have a preamble file lying around, or if we might try to
2061 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002062 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002063 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002064 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002065
Douglas Gregorabc563f2010-07-19 21:46:24 +00002066 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002067 getDiagnostics().Reset();
2068 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002069 if (OverrideMainBuffer)
2070 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002071
Douglas Gregor175c4a92010-07-23 23:58:40 +00002072 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002073 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002074
2075 // If we're caching global code-completion results, and the top-level
2076 // declarations have changed, clear out the code-completion cache.
2077 if (!Result && ShouldCacheCodeCompletionResults &&
2078 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2079 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002080
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002081 // We now need to clear out the completion info related to this translation
2082 // unit; it'll be recreated if necessary.
2083 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002084
Douglas Gregor175c4a92010-07-23 23:58:40 +00002085 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002086}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002087
Douglas Gregor87c08a52010-08-13 22:48:40 +00002088//----------------------------------------------------------------------------//
2089// Code completion
2090//----------------------------------------------------------------------------//
2091
2092namespace {
2093 /// \brief Code completion consumer that combines the cached code-completion
2094 /// results from an ASTUnit with the code-completion results provided to it,
2095 /// then passes the result on to
2096 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002097 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002098 ASTUnit &AST;
2099 CodeCompleteConsumer &Next;
2100
2101 public:
2102 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002103 const CodeCompleteOptions &CodeCompleteOpts)
2104 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2105 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002106 {
2107 // Compute the set of contexts in which we will look when we don't have
2108 // any information about the specific context.
2109 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002110 = (1LL << CodeCompletionContext::CCC_TopLevel)
2111 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2112 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2113 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2114 | (1LL << CodeCompletionContext::CCC_Statement)
2115 | (1LL << CodeCompletionContext::CCC_Expression)
2116 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2117 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2118 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2119 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2120 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2121 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2122 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002123
David Blaikie4e4d0842012-03-11 07:00:24 +00002124 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002125 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2126 | (1LL << CodeCompletionContext::CCC_UnionTag)
2127 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002128 }
2129
2130 virtual void ProcessCodeCompleteResults(Sema &S,
2131 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002132 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002133 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002134
2135 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2136 OverloadCandidate *Candidates,
2137 unsigned NumCandidates) {
2138 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2139 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002140
Douglas Gregordae68752011-02-01 22:57:45 +00002141 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002142 return Next.getAllocator();
2143 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002144
2145 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2146 return Next.getCodeCompletionTUInfo();
2147 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002148 };
2149}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002150
Douglas Gregor5f808c22010-08-16 21:18:39 +00002151/// \brief Helper function that computes which global names are hidden by the
2152/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002153static void CalculateHiddenNames(const CodeCompletionContext &Context,
2154 CodeCompletionResult *Results,
2155 unsigned NumResults,
2156 ASTContext &Ctx,
2157 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002158 bool OnlyTagNames = false;
2159 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002160 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002161 case CodeCompletionContext::CCC_TopLevel:
2162 case CodeCompletionContext::CCC_ObjCInterface:
2163 case CodeCompletionContext::CCC_ObjCImplementation:
2164 case CodeCompletionContext::CCC_ObjCIvarList:
2165 case CodeCompletionContext::CCC_ClassStructUnion:
2166 case CodeCompletionContext::CCC_Statement:
2167 case CodeCompletionContext::CCC_Expression:
2168 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002169 case CodeCompletionContext::CCC_DotMemberAccess:
2170 case CodeCompletionContext::CCC_ArrowMemberAccess:
2171 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002172 case CodeCompletionContext::CCC_Namespace:
2173 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002174 case CodeCompletionContext::CCC_Name:
2175 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002176 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002177 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002178 break;
2179
2180 case CodeCompletionContext::CCC_EnumTag:
2181 case CodeCompletionContext::CCC_UnionTag:
2182 case CodeCompletionContext::CCC_ClassOrStructTag:
2183 OnlyTagNames = true;
2184 break;
2185
2186 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002187 case CodeCompletionContext::CCC_MacroName:
2188 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002189 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002190 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002191 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002192 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002193 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002194 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002195 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002196 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2197 case CodeCompletionContext::CCC_ObjCClassMessage:
2198 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002199 // We're looking for nothing, or we're looking for names that cannot
2200 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002201 return;
2202 }
2203
John McCall0a2c5e22010-08-25 06:19:51 +00002204 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002205 for (unsigned I = 0; I != NumResults; ++I) {
2206 if (Results[I].Kind != Result::RK_Declaration)
2207 continue;
2208
2209 unsigned IDNS
2210 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2211
2212 bool Hiding = false;
2213 if (OnlyTagNames)
2214 Hiding = (IDNS & Decl::IDNS_Tag);
2215 else {
2216 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002217 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2218 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002219 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002220 HiddenIDNS |= Decl::IDNS_Tag;
2221 Hiding = (IDNS & HiddenIDNS);
2222 }
2223
2224 if (!Hiding)
2225 continue;
2226
2227 DeclarationName Name = Results[I].Declaration->getDeclName();
2228 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2229 HiddenNames.insert(Identifier->getName());
2230 else
2231 HiddenNames.insert(Name.getAsString());
2232 }
2233}
2234
2235
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002236void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2237 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002238 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002239 unsigned NumResults) {
2240 // Merge the results we were given with the results we cached.
2241 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002242 uint64_t InContexts =
2243 Context.getKind() == CodeCompletionContext::CCC_Recovery
2244 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002245 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002246 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002247 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002248 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002249 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002250 C = AST.cached_completion_begin(),
2251 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002252 C != CEnd; ++C) {
2253 // If the context we are in matches any of the contexts we are
2254 // interested in, we'll add this result.
2255 if ((C->ShowInContexts & InContexts) == 0)
2256 continue;
2257
2258 // If we haven't added any results previously, do so now.
2259 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002260 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2261 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002262 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2263 AddedResult = true;
2264 }
2265
Douglas Gregor5f808c22010-08-16 21:18:39 +00002266 // Determine whether this global completion result is hidden by a local
2267 // completion result. If so, skip it.
2268 if (C->Kind != CXCursor_MacroDefinition &&
2269 HiddenNames.count(C->Completion->getTypedText()))
2270 continue;
2271
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002272 // Adjust priority based on similar type classes.
2273 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002274 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275 if (!Context.getPreferredType().isNull()) {
2276 if (C->Kind == CXCursor_MacroDefinition) {
2277 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002278 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002279 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002280 } else if (C->Type) {
2281 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002282 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002283 Context.getPreferredType().getUnqualifiedType());
2284 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2285 if (ExpectedSTC == C->TypeClass) {
2286 // We know this type is similar; check for an exact match.
2287 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002288 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002289 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002290 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2292 Priority /= CCF_ExactTypeMatch;
2293 else
2294 Priority /= CCF_SimilarTypeMatch;
2295 }
2296 }
2297 }
2298
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002299 // Adjust the completion string, if required.
2300 if (C->Kind == CXCursor_MacroDefinition &&
2301 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2302 // Create a new code-completion string that just contains the
2303 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002304 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2305 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002306 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002307 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002308 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002309 }
2310
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002311 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002312 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002313 }
2314
2315 // If we did not add any cached completion results, just forward the
2316 // results we were given to the next consumer.
2317 if (!AddedResult) {
2318 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2319 return;
2320 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002321
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002322 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2323 AllResults.size());
2324}
2325
2326
2327
Chris Lattner5f9e2722011-07-23 10:55:15 +00002328void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002329 RemappedFile *RemappedFiles,
2330 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002331 bool IncludeMacros,
2332 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002333 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002334 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002335 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002336 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002337 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2338 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002339 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002340 return;
2341
Douglas Gregor213f18b2010-10-28 15:44:59 +00002342 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002343 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002344 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002345
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002346 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002347 CCInvocation(new CompilerInvocation(*Invocation));
2348
2349 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002350 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002351 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002352
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002353 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2354 CachedCompletionResults.empty();
2355 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2356 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2357 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2358
2359 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2360
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002361 FrontendOpts.CodeCompletionAt.FileName = File;
2362 FrontendOpts.CodeCompletionAt.Line = Line;
2363 FrontendOpts.CodeCompletionAt.Column = Column;
2364
2365 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002366 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002368 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002369
2370 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002371 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2372 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002373
Ted Kremenek4f327862011-03-21 18:40:17 +00002374 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002375 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002376
2377 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002378 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002379 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002380 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002381 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002383
2384 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002385 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002386 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002387 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002388 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002389 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390 }
2391
2392 // Inform the target of the language options.
2393 //
2394 // FIXME: We shouldn't need to do this, the target should be immutable once
2395 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002396 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397
Ted Kremenek03201fb2011-03-21 18:40:07 +00002398 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002399 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002400 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002401 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002402 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002403 "IR inputs not support here!");
2404
2405
2406 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002407 Clang->setFileManager(&FileMgr);
2408 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409
2410 // Remap files.
2411 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002412 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002413 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002414 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2415 if (const llvm::MemoryBuffer *
2416 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2417 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2418 OwnedBuffers.push_back(memBuf);
2419 } else {
2420 const char *fname = fileOrBuf.get<const char *>();
2421 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2422 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002423 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002424
Douglas Gregor87c08a52010-08-13 22:48:40 +00002425 // Use the code completion consumer we were given, but adding any cached
2426 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002427 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002428 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002429 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002430
Douglas Gregordf95a132010-08-09 20:45:32 +00002431 // If we have a precompiled preamble, try to use it. We only allow
2432 // the use of the precompiled preamble if we're if the completion
2433 // point is within the main file, after the end of the precompiled
2434 // preamble.
2435 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002436 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002437 using llvm::sys::FileStatus;
2438 llvm::sys::PathWithStatus CompleteFilePath(File);
2439 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2440 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2441 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002442 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2443 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002444 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002445 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002446 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002447 }
2448
2449 // If the main file has been overridden due to the use of a preamble,
2450 // make that override happen and introduce the preamble.
2451 if (OverrideMainBuffer) {
2452 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2453 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2454 PreprocessorOpts.PrecompiledPreambleBytes.second
2455 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002456 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002457 PreprocessorOpts.DisablePCHValidation = true;
2458
Douglas Gregor2283d792010-08-20 00:59:43 +00002459 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002460 } else {
2461 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2462 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002463 }
2464
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002465 // Disable the preprocessing record if modules are not enabled.
2466 if (!Clang->getLangOpts().Modules)
2467 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002468
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002469 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002470 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002471 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002472 Act->Execute();
2473 Act->EndSourceFile();
2474 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002475}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002476
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002477bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002478 // Write to a temporary file and later rename it to the actual file, to avoid
2479 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002480 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002481 TempPath = File;
2482 TempPath += "-%%%%%%%%";
2483 int fd;
2484 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2485 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002486 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002487
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002488 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2489 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002490 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002491
2492 serialize(Out);
2493 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002494 if (Out.has_error()) {
2495 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002496 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002497 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002498
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002499 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002500 bool exists;
2501 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002502 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002503 }
2504
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002505 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002506}
2507
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002508static bool serializeUnit(ASTWriter &Writer,
2509 SmallVectorImpl<char> &Buffer,
2510 Sema &S,
2511 bool hasErrors,
2512 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002513 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002514
2515 // Write the generated bitstream to "Out".
2516 if (!Buffer.empty())
2517 OS.write(Buffer.data(), Buffer.size());
2518
2519 return false;
2520}
2521
Chris Lattner5f9e2722011-07-23 10:55:15 +00002522bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002523 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002524
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002525 if (WriterData)
2526 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2527 getSema(), hasErrors, OS);
2528
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002529 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002530 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002531 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002532 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002533}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002534
2535typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2536
2537static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2538 unsigned Raw = L.getRawEncoding();
2539 const unsigned MacroBit = 1U << 31;
2540 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2541 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2542}
2543
2544void ASTUnit::TranslateStoredDiagnostics(
2545 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002546 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002547 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548 const SmallVectorImpl<StoredDiagnostic> &Diags,
2549 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002550 // The stored diagnostic has the old source manager in it; update
2551 // the locations to refer into the new source manager. We also need to remap
2552 // all the locations to the new view. This includes the diag location, any
2553 // associated source ranges, and the source ranges of associated fix-its.
2554 // FIXME: There should be a cleaner way to do this.
2555
Chris Lattner5f9e2722011-07-23 10:55:15 +00002556 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002557 Result.reserve(Diags.size());
2558 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002559 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002560 assert(Mod && "Don't have preamble module");
2561 SLocRemap &Remap = Mod->SLocRemap;
2562 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2563 // Rebuild the StoredDiagnostic.
2564 const StoredDiagnostic &SD = Diags[I];
2565 SourceLocation L = SD.getLocation();
2566 TranslateSLoc(L, Remap);
2567 FullSourceLoc Loc(L, SrcMgr);
2568
Chris Lattner5f9e2722011-07-23 10:55:15 +00002569 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002570 Ranges.reserve(SD.range_size());
2571 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2572 E = SD.range_end();
2573 I != E; ++I) {
2574 SourceLocation BL = I->getBegin();
2575 TranslateSLoc(BL, Remap);
2576 SourceLocation EL = I->getEnd();
2577 TranslateSLoc(EL, Remap);
2578 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2579 }
2580
Chris Lattner5f9e2722011-07-23 10:55:15 +00002581 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002582 FixIts.reserve(SD.fixit_size());
2583 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2584 E = SD.fixit_end();
2585 I != E; ++I) {
2586 FixIts.push_back(FixItHint());
2587 FixItHint &FH = FixIts.back();
2588 FH.CodeToInsert = I->CodeToInsert;
2589 SourceLocation BL = I->RemoveRange.getBegin();
2590 TranslateSLoc(BL, Remap);
2591 SourceLocation EL = I->RemoveRange.getEnd();
2592 TranslateSLoc(EL, Remap);
2593 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2594 I->RemoveRange.isTokenRange());
2595 }
2596
2597 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2598 SD.getMessage(), Loc, Ranges, FixIts));
2599 }
2600 Result.swap(Out);
2601}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002602
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002603static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2604 std::pair<unsigned, Decl *> R) {
2605 return L.first < R.first;
2606}
2607
2608void ASTUnit::addFileLevelDecl(Decl *D) {
2609 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002610
2611 // We only care about local declarations.
2612 if (D->isFromASTFile())
2613 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002614
2615 SourceManager &SM = *SourceMgr;
2616 SourceLocation Loc = D->getLocation();
2617 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2618 return;
2619
2620 // We only keep track of the file-level declarations of each file.
2621 if (!D->getLexicalDeclContext()->isFileContext())
2622 return;
2623
2624 SourceLocation FileLoc = SM.getFileLoc(Loc);
2625 assert(SM.isLocalSourceLocation(FileLoc));
2626 FileID FID;
2627 unsigned Offset;
2628 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2629 if (FID.isInvalid())
2630 return;
2631
2632 LocDeclsTy *&Decls = FileDecls[FID];
2633 if (!Decls)
2634 Decls = new LocDeclsTy();
2635
2636 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2637
2638 if (Decls->empty() || Decls->back().first <= Offset) {
2639 Decls->push_back(LocDecl);
2640 return;
2641 }
2642
2643 LocDeclsTy::iterator
2644 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2645
2646 Decls->insert(I, LocDecl);
2647}
2648
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002649void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2650 SmallVectorImpl<Decl *> &Decls) {
2651 if (File.isInvalid())
2652 return;
2653
2654 if (SourceMgr->isLoadedFileID(File)) {
2655 assert(Ctx->getExternalSource() && "No external source!");
2656 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2657 Decls);
2658 }
2659
2660 FileDeclsTy::iterator I = FileDecls.find(File);
2661 if (I == FileDecls.end())
2662 return;
2663
2664 LocDeclsTy &LocDecls = *I->second;
2665 if (LocDecls.empty())
2666 return;
2667
2668 LocDeclsTy::iterator
2669 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2670 std::make_pair(Offset, (Decl*)0), compLocDecl);
2671 if (BeginIt != LocDecls.begin())
2672 --BeginIt;
2673
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002674 // If we are pointing at a top-level decl inside an objc container, we need
2675 // to backtrack until we find it otherwise we will fail to report that the
2676 // region overlaps with an objc container.
2677 while (BeginIt != LocDecls.begin() &&
2678 BeginIt->second->isTopLevelDeclInObjCContainer())
2679 --BeginIt;
2680
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002681 LocDeclsTy::iterator
2682 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2683 std::make_pair(Offset+Length, (Decl*)0),
2684 compLocDecl);
2685 if (EndIt != LocDecls.end())
2686 ++EndIt;
2687
2688 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2689 Decls.push_back(DIt->second);
2690}
2691
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002692SourceLocation ASTUnit::getLocation(const FileEntry *File,
2693 unsigned Line, unsigned Col) const {
2694 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002695 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002696 return SM.getMacroArgExpandedLocation(Loc);
2697}
2698
2699SourceLocation ASTUnit::getLocation(const FileEntry *File,
2700 unsigned Offset) const {
2701 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002702 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002703 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2704}
2705
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002706/// \brief If \arg Loc is a loaded location from the preamble, returns
2707/// the corresponding local location of the main file, otherwise it returns
2708/// \arg Loc.
2709SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2710 FileID PreambleID;
2711 if (SourceMgr)
2712 PreambleID = SourceMgr->getPreambleFileID();
2713
2714 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2715 return Loc;
2716
2717 unsigned Offs;
2718 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2719 SourceLocation FileLoc
2720 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2721 return FileLoc.getLocWithOffset(Offs);
2722 }
2723
2724 return Loc;
2725}
2726
2727/// \brief If \arg Loc is a local location of the main file but inside the
2728/// preamble chunk, returns the corresponding loaded location from the
2729/// preamble, otherwise it returns \arg Loc.
2730SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2731 FileID PreambleID;
2732 if (SourceMgr)
2733 PreambleID = SourceMgr->getPreambleFileID();
2734
2735 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2736 return Loc;
2737
2738 unsigned Offs;
2739 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2740 Offs < Preamble.size()) {
2741 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2742 return FileLoc.getLocWithOffset(Offs);
2743 }
2744
2745 return Loc;
2746}
2747
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002748bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2749 FileID FID;
2750 if (SourceMgr)
2751 FID = SourceMgr->getPreambleFileID();
2752
2753 if (Loc.isInvalid() || FID.isInvalid())
2754 return false;
2755
2756 return SourceMgr->isInFileID(Loc, FID);
2757}
2758
2759bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2760 FileID FID;
2761 if (SourceMgr)
2762 FID = SourceMgr->getMainFileID();
2763
2764 if (Loc.isInvalid() || FID.isInvalid())
2765 return false;
2766
2767 return SourceMgr->isInFileID(Loc, FID);
2768}
2769
2770SourceLocation ASTUnit::getEndOfPreambleFileID() {
2771 FileID FID;
2772 if (SourceMgr)
2773 FID = SourceMgr->getPreambleFileID();
2774
2775 if (FID.isInvalid())
2776 return SourceLocation();
2777
2778 return SourceMgr->getLocForEndOfFile(FID);
2779}
2780
2781SourceLocation ASTUnit::getStartOfMainFileID() {
2782 FileID FID;
2783 if (SourceMgr)
2784 FID = SourceMgr->getMainFileID();
2785
2786 if (FID.isInvalid())
2787 return SourceLocation();
2788
2789 return SourceMgr->getLocForStartOfFile(FID);
2790}
2791
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002792std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2793ASTUnit::getLocalPreprocessingEntities() const {
2794 if (isMainFileAST()) {
2795 serialization::ModuleFile &
2796 Mod = Reader->getModuleManager().getPrimaryModule();
2797 return Reader->getModulePreprocessedEntities(Mod);
2798 }
2799
2800 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2801 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2802
2803 return std::make_pair(PreprocessingRecord::iterator(),
2804 PreprocessingRecord::iterator());
2805}
2806
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002807bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002808 if (isMainFileAST()) {
2809 serialization::ModuleFile &
2810 Mod = Reader->getModuleManager().getPrimaryModule();
2811 ASTReader::ModuleDeclIterator MDI, MDE;
2812 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2813 for (; MDI != MDE; ++MDI) {
2814 if (!Fn(context, *MDI))
2815 return false;
2816 }
2817
2818 return true;
2819 }
2820
2821 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2822 TLEnd = top_level_end();
2823 TL != TLEnd; ++TL) {
2824 if (!Fn(context, *TL))
2825 return false;
2826 }
2827
2828 return true;
2829}
2830
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002831namespace {
2832struct PCHLocatorInfo {
2833 serialization::ModuleFile *Mod;
2834 PCHLocatorInfo() : Mod(0) {}
2835};
2836}
2837
2838static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2839 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2840 switch (M.Kind) {
2841 case serialization::MK_Module:
2842 return true; // skip dependencies.
2843 case serialization::MK_PCH:
2844 Info.Mod = &M;
2845 return true; // found it.
2846 case serialization::MK_Preamble:
2847 return false; // look in dependencies.
2848 case serialization::MK_MainFile:
2849 return false; // look in dependencies.
2850 }
2851
2852 return true;
2853}
2854
2855const FileEntry *ASTUnit::getPCHFile() {
2856 if (!Reader)
2857 return 0;
2858
2859 PCHLocatorInfo Info;
2860 Reader->getModuleManager().visit(PCHLocator, &Info);
2861 if (Info.Mod)
2862 return Info.Mod->File;
2863
2864 return 0;
2865}
2866
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002867bool ASTUnit::isModuleFile() {
2868 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2869}
2870
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002871void ASTUnit::PreambleData::countLines() const {
2872 NumLines = 0;
2873 if (empty())
2874 return;
2875
2876 for (std::vector<char>::const_iterator
2877 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2878 if (*I == '\n')
2879 ++NumLines;
2880 }
2881 if (Buffer.back() != '\n')
2882 ++NumLines;
2883}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002884
2885#ifndef NDEBUG
2886ASTUnit::ConcurrencyState::ConcurrencyState() {
2887 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2888}
2889
2890ASTUnit::ConcurrencyState::~ConcurrencyState() {
2891 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2892}
2893
2894void ASTUnit::ConcurrencyState::start() {
2895 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2896 assert(acquired && "Concurrent access to ASTUnit!");
2897}
2898
2899void ASTUnit::ConcurrencyState::finish() {
2900 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2901}
2902
2903#else // NDEBUG
2904
2905ASTUnit::ConcurrencyState::ConcurrencyState() {}
2906ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2907void ASTUnit::ConcurrencyState::start() {}
2908void ASTUnit::ConcurrencyState::finish() {}
2909
2910#endif