blob: 1b4e5a0b39af8fd3f452264989be8b3136a65258 [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() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000239 // If we loaded from an AST file, balance out the BeginSourceFile call.
240 if (MainFileIsAST && getDiagnostics().getClient()) {
241 getDiagnostics().getClient()->EndSourceFile();
242 }
243
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000244 clearFileLevelDecls();
245
Ted Kremenek1872b312011-10-27 17:55:18 +0000246 // Clean up the temporary files and the preamble file.
247 removeOnDiskEntry(this);
248
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 // Free the buffers associated with remapped files. We are required to
250 // perform this operation here because we explicitly request that the
251 // compiler instance *not* free these buffers for each invocation of the
252 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000253 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000254 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
255 for (PreprocessorOptions::remapped_file_buffer_iterator
256 FB = PPOpts.remapped_file_buffer_begin(),
257 FBEnd = PPOpts.remapped_file_buffer_end();
258 FB != FBEnd;
259 ++FB)
260 delete FB->second;
261 }
Douglas Gregor28233422010-07-27 14:52:07 +0000262
263 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000264 delete PreambleBuffer;
265
Douglas Gregor213f18b2010-10-28 15:44:59 +0000266 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000267
268 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000269 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000270 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
271 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000272}
273
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000274void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
275
Douglas Gregor8071e422010-08-15 06:18:01 +0000276/// \brief Determine the set of code-completion contexts in which this
277/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000278static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000279 const LangOptions &LangOpts,
280 bool &IsNestedNameSpecifier) {
281 IsNestedNameSpecifier = false;
282
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<UsingShadowDecl>(ND))
284 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
285 if (!ND)
286 return 0;
287
Richard Smith026b3582012-08-14 03:13:00 +0000288 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000289 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
290 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
291 // Types can appear in these contexts.
292 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
294 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
295 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
296 | (1LL << CodeCompletionContext::CCC_Statement)
297 | (1LL << CodeCompletionContext::CCC_Type)
298 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // In C++, types can appear in expressions contexts (for functional casts).
301 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
304 // In Objective-C, message sends can send interfaces. In Objective-C++,
305 // all types are available due to functional casts.
306 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000308
309 // In Objective-C, you can only be a subclass of another Objective-C class
310 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000312
313 // Deal with tag names.
314 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000315 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000316
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000318 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000320 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000322 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 else
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000328 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
331 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
333 | (1LL << CodeCompletionContext::CCC_Expression)
334 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
335 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000337 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000338 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342
343 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000344 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000345 }
346
347 return Contexts;
348}
349
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350void ASTUnit::CacheCodeCompletionResults() {
351 if (!TheSema)
352 return;
353
Douglas Gregor213f18b2010-10-28 15:44:59 +0000354 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000355 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Clear out the previous results.
358 ClearCachedCompletionResults();
359
360 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000361 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000362 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000364 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000365 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000367
368 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
370
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
372 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000374 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000376 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000377 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000378 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000379 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000380 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000381 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000382 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000383 CachedResult.Priority = Results[I].Priority;
384 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000385 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 // Keep track of the type of this completion in an ASTContext-agnostic
388 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000389 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000390 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 CachedResult.Type = 0;
393 } else {
394 CanQualType CanUsageType
395 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
396 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
397
398 // Determine whether we have already seen this type. If so, we save
399 // ourselves the work of formatting the type string by using the
400 // temporary, CanQualType-based hash table to find the associated value.
401 unsigned &TypeValue = CompletionTypes[CanUsageType];
402 if (TypeValue == 0) {
403 TypeValue = CompletionTypes.size();
404 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
405 = TypeValue;
406 }
407
408 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000409 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000410
Douglas Gregor8071e422010-08-15 06:18:01 +0000411 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000412
413 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
416 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000417 uint64_t NNSContexts
418 = (1LL << CodeCompletionContext::CCC_TopLevel)
419 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
420 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
421 | (1LL << CodeCompletionContext::CCC_Statement)
422 | (1LL << CodeCompletionContext::CCC_Expression)
423 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
424 | (1LL << CodeCompletionContext::CCC_EnumTag)
425 | (1LL << CodeCompletionContext::CCC_UnionTag)
426 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
427 | (1LL << CodeCompletionContext::CCC_Type)
428 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
429 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000430
431 if (isa<NamespaceDecl>(Results[I].Declaration) ||
432 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000433 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000434
435 if (unsigned RemainingContexts
436 = NNSContexts & ~CachedResult.ShowInContexts) {
437 // If there any contexts where this completion can be a
438 // nested-name-specifier but isn't already an option, create a
439 // nested-name-specifier completion.
440 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000441 CachedResult.Completion
442 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000443 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000444 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000445 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000446 CachedResult.ShowInContexts = RemainingContexts;
447 CachedResult.Priority = CCP_NestedNameSpecifier;
448 CachedResult.TypeClass = STC_Void;
449 CachedResult.Type = 0;
450 CachedCompletionResults.push_back(CachedResult);
451 }
452 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000453 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000454 }
455
Douglas Gregor87c08a52010-08-13 22:48:40 +0000456 case Result::RK_Keyword:
457 case Result::RK_Pattern:
458 // Ignore keywords and patterns; we don't care, since they are so
459 // easily regenerated.
460 break;
461
462 case Result::RK_Macro: {
463 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000464 CachedResult.Completion
465 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000466 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000467 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000468 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000470 = (1LL << CodeCompletionContext::CCC_TopLevel)
471 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
472 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
473 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
474 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
475 | (1LL << CodeCompletionContext::CCC_Statement)
476 | (1LL << CodeCompletionContext::CCC_Expression)
477 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
478 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
479 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
480 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
481 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000482
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedResult.Priority = Results[I].Priority;
484 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000485 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000486 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000487 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000488 CachedCompletionResults.push_back(CachedResult);
489 break;
490 }
491 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000493
494 // Save the current top-level hash value.
495 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
498void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000499 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000500 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000501 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000502}
503
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504namespace {
505
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000506/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000508class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 LangOptions &LangOpt;
512 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000513 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000514 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000521 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000522 HeaderSearch &HSI,
523 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000524 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000525 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000526 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
527 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor43998902012-10-25 00:09:28 +0000528 Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000529 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000531 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000532 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000533 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000534 return false;
535
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000536 LangOpt = LangOpts;
537 InitializedLanguage = true;
538
539 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000540 return false;
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000543 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000544 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000545 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000546 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000547 return false;
548
Douglas Gregor57016dd2012-10-16 23:40:58 +0000549 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000550 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
551 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000552
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000553 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 return false;
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000557 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000558 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000561 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000562 Counter = Value;
563 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000564
565private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000566 void updated() {
567 if (!Target || !InitializedLanguage)
568 return;
569
570 // Inform the target of the language options.
571 //
572 // FIXME: We shouldn't need to do this, the target should be immutable once
573 // created. This complexity should be lifted elsewhere.
574 Target->setForcedLangOptions(LangOpt);
575
576 // Initialize the preprocessor.
577 PP.Initialize(*Target);
578
579 // Initialize the ASTContext
580 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000581
582 // We didn't have access to the comment options when the ASTContext was
583 // constructed, so register them now.
584 Context.getCommentCommandTraits().registerCommentOptions(
585 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000586 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000587};
588
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000589 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000590class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000591 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000592 SourceManager *SourceMgr;
593
Douglas Gregora88084b2010-02-18 18:08:43 +0000594public:
David Blaikie26e7a902011-09-26 00:01:39 +0000595 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000597 : StoredDiags(StoredDiags), SourceMgr(0) { }
598
599 virtual void BeginSourceFile(const LangOptions &LangOpts,
600 const Preprocessor *PP = 0) {
601 if (PP)
602 SourceMgr = &PP->getSourceManager();
603 }
604
David Blaikied6471f72011-09-25 23:23:43 +0000605 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000606 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000607
608 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
609 // Just drop any diagnostics that come from cloned consumers; they'll
610 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000611 // FIXME: We'd like to be able to capture these somehow, even if it's just
612 // file/line/column, because they could occur when parsing module maps or
613 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000614 return new IgnoringDiagConsumer();
615 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000616};
617
618/// \brief RAII object that optionally captures diagnostics, if
619/// there is no diagnostic client to capture them already.
620class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000621 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000622 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000623 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000624
625public:
David Blaikied6471f72011-09-25 23:23:43 +0000626 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000627 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000628 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000629 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000630 if (RequestCapture || Diags.getClient() == 0) {
631 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000632 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000633 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000634 }
635
636 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000637 if (Diags.getClient() == &Client) {
638 Diags.takeClient();
639 Diags.setClient(PreviousClient);
640 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000641 }
642};
643
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644} // anonymous namespace
645
David Blaikie26e7a902011-09-26 00:01:39 +0000646void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000647 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000648 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000649 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000650
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000651 // Only record the diagnostic if it's part of the source manager we know
652 // about. This effectively drops diagnostics from modules we're building.
653 // FIXME: In the long run, ee don't want to drop source managers from modules.
654 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
655 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000656}
657
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000658ASTDeserializationListener *ASTUnit::getDeserializationListener() {
659 if (WriterData)
660 return &WriterData->Writer;
661 return 0;
662}
663
Chris Lattner5f9e2722011-07-23 10:55:15 +0000664llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000665 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000666 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000667 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000668}
669
Douglas Gregore47be3e2010-11-11 00:39:14 +0000670/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000671void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000672 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000673 ASTUnit &AST, bool CaptureDiagnostics) {
674 if (!Diags.getPtr()) {
675 // No diagnostics engine was provided, so create our own diagnostics object
676 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000677 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000678 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000679 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000680 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000681 Client,
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000682 /*ShouldOwnClient=*/true,
683 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000684 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000685 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000686 }
687}
688
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000689ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000690 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000691 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000692 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000693 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000694 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000695 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000696 bool AllowPCHWithCompilerErrors,
697 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000698 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000699
700 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000701 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
702 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000703 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
704 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000705 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000706
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000707 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000708
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000709 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000710 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000711 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000712 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000713 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000714 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000715 AST->getFileManager(),
716 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000717 AST->HSOpts = new HeaderSearchOptions();
718
719 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
720 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000721 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000722 AST->ASTFileLangOpts,
723 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000724
Douglas Gregor4db64a42010-01-23 00:14:00 +0000725 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000726 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
727 if (const llvm::MemoryBuffer *
728 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
729 // Create the file entry for the file that we're mapping from.
730 const FileEntry *FromFile
731 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
732 memBuf->getBufferSize(),
733 0);
734 if (!FromFile) {
735 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
736 << RemappedFiles[I].first;
737 delete memBuf;
738 continue;
739 }
740
741 // Override the contents of the "from" file with the contents of
742 // the "to" file.
743 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
744
745 } else {
746 const char *fname = fileOrBuf.get<const char *>();
747 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
748 if (!ToFile) {
749 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
750 << RemappedFiles[I].first << fname;
751 continue;
752 }
753
754 // Create the file entry for the file that we're mapping from.
755 const FileEntry *FromFile
756 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
757 ToFile->getSize(),
758 0);
759 if (!FromFile) {
760 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
761 << RemappedFiles[I].first;
762 delete memBuf;
763 continue;
764 }
765
766 // Override the contents of the "from" file with the contents of
767 // the "to" file.
768 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000769 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000770 }
771
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000774 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000775 unsigned Counter;
776
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000777 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778
Douglas Gregor36a16492012-10-24 17:46:57 +0000779 AST->PP = new Preprocessor(new PreprocessorOptions(),
780 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000781 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
782 *AST,
783 /*IILookup=*/0,
784 /*OwnsHeaderSearch=*/false,
785 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000786 Preprocessor &PP = *AST->PP;
787
788 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
789 AST->getSourceManager(),
790 /*Target=*/0,
791 PP.getIdentifierTable(),
792 PP.getSelectorTable(),
793 PP.getBuiltinInfo(),
794 /* size_reserve = */0,
795 /*DelayInitialization=*/true);
796 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000797
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000798 bool disableValid = false;
799 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
800 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000801 Reader.reset(new ASTReader(PP, Context,
802 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000803 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000804 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000805
806 // Recover resources if we crash before exiting this method.
807 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
808 ReaderCleanup(Reader.get());
809
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000810 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000811 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000812 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000813 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000814
Douglas Gregor38295be2012-10-22 23:51:00 +0000815 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000816 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000817 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000818 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000820 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000821 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000822 case ASTReader::OutOfDate:
823 case ASTReader::VersionMismatch:
824 case ASTReader::ConfigurationMismatch:
825 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000826 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000827 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000830 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
831
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000832 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000834 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000835 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000836 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000837 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000838 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000839
840 // Unregister the cleanup for ASTReader. It will get cleaned up
841 // by the ASTUnit cleanup.
842 ReaderCleanup.unregister();
843
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000844 Context.setExternalSource(Source);
845
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000846 // Create an AST consumer, even though it isn't used.
847 AST->Consumer.reset(new ASTConsumer);
848
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000849 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000850 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
851 AST->TheSema->Initialize();
852 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000853 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000854
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000855 // Tell the diagnostic client that we have started a source file.
856 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
857
Mike Stump1eb44332009-09-09 15:08:12 +0000858 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000859}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000860
861namespace {
862
Douglas Gregor9b7db622011-02-16 18:16:54 +0000863/// \brief Preprocessor callback class that updates a hash value with the names
864/// of all macros that have been defined by the translation unit.
865class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
866 unsigned &Hash;
867
868public:
869 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
870
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000871 virtual void MacroDefined(const Token &MacroNameTok,
872 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000873 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
874 }
875};
876
877/// \brief Add the given declaration to the hash of all top-level entities.
878void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
879 if (!D)
880 return;
881
882 DeclContext *DC = D->getDeclContext();
883 if (!DC)
884 return;
885
886 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
887 return;
888
889 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
890 if (ND->getIdentifier())
891 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
892 else if (DeclarationName Name = ND->getDeclName()) {
893 std::string NameStr = Name.getAsString();
894 Hash = llvm::HashString(NameStr, Hash);
895 }
896 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000897 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000898}
899
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000900class TopLevelDeclTrackerConsumer : public ASTConsumer {
901 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000902 unsigned &Hash;
903
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000904public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000905 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
906 : Unit(_Unit), Hash(Hash) {
907 Hash = 0;
908 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000909
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000910 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000911 if (!D)
912 return;
913
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000914 // FIXME: Currently ObjC method declarations are incorrectly being
915 // reported as top-level declarations, even though their DeclContext
916 // is the containing ObjC @interface/@implementation. This is a
917 // fundamental problem in the parser right now.
918 if (isa<ObjCMethodDecl>(D))
919 return;
920
921 AddTopLevelDeclarationToHash(D, Hash);
922 Unit.addTopLevelDecl(D);
923
924 handleFileLevelDecl(D);
925 }
926
927 void handleFileLevelDecl(Decl *D) {
928 Unit.addFileLevelDecl(D);
929 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
930 for (NamespaceDecl::decl_iterator
931 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
932 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000933 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000934 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000935
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000936 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000937 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
938 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000939 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000940 }
941
Sebastian Redl27372b42010-08-11 18:52:41 +0000942 // We're not interested in "interesting" decls.
943 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000944
945 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
946 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
947 handleTopLevelDecl(*it);
948 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000949
950 virtual ASTDeserializationListener *GetASTDeserializationListener() {
951 return Unit.getDeserializationListener();
952 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000953};
954
955class TopLevelDeclTrackerAction : public ASTFrontendAction {
956public:
957 ASTUnit &Unit;
958
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000959 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000960 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000961 CI.getPreprocessor().addPPCallbacks(
962 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
963 return new TopLevelDeclTrackerConsumer(Unit,
964 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000965 }
966
967public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000968 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
969
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000970 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000971 virtual TranslationUnitKind getTranslationUnitKind() {
972 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000973 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000974};
975
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000976class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000977 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000978 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000979 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000980
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000982 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000983 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000984 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000985 Hash(Unit.getCurrentTopLevelHashValue()) {
986 Hash = 0;
987 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000988
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000989 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000990 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
991 Decl *D = *it;
992 // FIXME: Currently ObjC method declarations are incorrectly being
993 // reported as top-level declarations, even though their DeclContext
994 // is the containing ObjC @interface/@implementation. This is a
995 // fundamental problem in the parser right now.
996 if (isa<ObjCMethodDecl>(D))
997 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000998 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000999 TopLevelDecls.push_back(D);
1000 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001001 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001002 }
1003
1004 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1005 PCHGenerator::HandleTranslationUnit(Ctx);
1006 if (!Unit.getDiagnostics().hasErrorOccurred()) {
1007 // Translate the top-level declarations we captured during
1008 // parsing into declaration IDs in the precompiled
1009 // preamble. This will allow us to deserialize those top-level
1010 // declarations when requested.
1011 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1012 Unit.addTopLevelDeclFromPreamble(
1013 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001014 }
1015 }
1016};
1017
1018class PrecompilePreambleAction : public ASTFrontendAction {
1019 ASTUnit &Unit;
1020
1021public:
1022 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1023
1024 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001025 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001026 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001027 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001028 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001029 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1030 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001031 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001032 return 0;
1033
Douglas Gregor832d6202011-07-22 16:35:34 +00001034 if (!CI.getFrontendOpts().RelocatablePCH)
1035 Sysroot.clear();
1036
Douglas Gregor9b7db622011-02-16 18:16:54 +00001037 CI.getPreprocessor().addPPCallbacks(
1038 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001039 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1040 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001041 }
1042
1043 virtual bool hasCodeCompletionSupport() const { return false; }
1044 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001045 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001046};
1047
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001048}
1049
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001050static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1051 StoredDiagnostics) {
1052 // Get rid of stored diagnostics except the ones from the driver which do not
1053 // have a source location.
1054 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1055 if (StoredDiagnostics[I].getLocation().isValid()) {
1056 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1057 --I;
1058 }
1059 }
1060}
1061
1062static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1063 StoredDiagnostics,
1064 SourceManager &SM) {
1065 // The stored diagnostic has the old source manager in it; update
1066 // the locations to refer into the new source manager. Since we've
1067 // been careful to make sure that the source manager's state
1068 // before and after are identical, so that we can reuse the source
1069 // location itself.
1070 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1071 if (StoredDiagnostics[I].getLocation().isValid()) {
1072 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1073 StoredDiagnostics[I].setLocation(Loc);
1074 }
1075 }
1076}
1077
Douglas Gregorabc563f2010-07-19 21:46:24 +00001078/// Parse the source file into a translation unit using the given compiler
1079/// invocation, replacing the current translation unit.
1080///
1081/// \returns True if a failure occurred that causes the ASTUnit not to
1082/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001083bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001084 delete SavedMainFileBuffer;
1085 SavedMainFileBuffer = 0;
1086
Ted Kremenek4f327862011-03-21 18:40:17 +00001087 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001088 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001089 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001090 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001091
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001093 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001094
1095 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001096 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1097 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001098
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001099 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001100 CCInvocation(new CompilerInvocation(*Invocation));
1101
1102 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001103 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001104
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001105 // Set up diagnostics, capturing any diagnostics that would
1106 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001107 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001108
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001109 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001110 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001111 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001112 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001113 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001114 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001115 }
1116
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001117 // Inform the target of the language options.
1118 //
1119 // FIXME: We shouldn't need to do this, the target should be immutable once
1120 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001121 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001122
Ted Kremenek03201fb2011-03-21 18:40:07 +00001123 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001124 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001125 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001126 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001127 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001128 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001129
Douglas Gregorabc563f2010-07-19 21:46:24 +00001130 // Configure the various subsystems.
1131 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001132 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001133 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001134 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001135 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1136 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001137 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001138 Ctx = 0;
1139 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001140 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001141
1142 // Clear out old caches and data.
1143 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001144 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001146
Douglas Gregorf128fed2010-08-20 00:02:33 +00001147 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001148 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001149 TopLevelDeclsInPreamble.clear();
1150 }
1151
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001152 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001153 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001154
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001155 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001156 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001157
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001158 // If the main file has been overridden due to the use of a preamble,
1159 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001160 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001161 if (OverrideMainBuffer) {
1162 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1163 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1164 PreprocessorOpts.PrecompiledPreambleBytes.second
1165 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001166 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001167 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001168
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001169 // The stored diagnostic has the old source manager in it; update
1170 // the locations to refer into the new source manager. Since we've
1171 // been careful to make sure that the source manager's state
1172 // before and after are identical, so that we can reuse the source
1173 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001174 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001175
1176 // Keep track of the override buffer;
1177 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001178 }
1179
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001180 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001181 new TopLevelDeclTrackerAction(*this));
1182
1183 // Recover resources if we crash before exiting this method.
1184 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1185 ActCleanup(Act.get());
1186
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001187 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001188 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001189
1190 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001191 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001192 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1193 getSourceManager(), PreambleDiagnostics,
1194 StoredDiagnostics);
1195 }
1196
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001197 if (!Act->Execute())
1198 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001199
1200 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001201
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001202 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001203
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001204 FailedParseDiagnostics.clear();
1205
Douglas Gregorabc563f2010-07-19 21:46:24 +00001206 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001207
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001208error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001209 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001210 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001211 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001212 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001213 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001214
1215 // Keep the ownership of the data in the ASTUnit because the client may
1216 // want to see the diagnostics.
1217 transferASTDataFromCompilerInstance(*Clang);
1218 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001219 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001220 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001221 return true;
1222}
1223
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224/// \brief Simple function to retrieve a path for a preamble precompiled header.
1225static std::string GetPreamblePCHPath() {
1226 // FIXME: This is lame; sys::Path should provide this function (in particular,
1227 // it should know how to find the temporary files dir).
1228 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001229 // FIXME: This is a hack so that we can override the preamble file during
1230 // crash-recovery testing, which is the only case where the preamble files
1231 // are not necessarily cleaned up.
1232 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1233 if (TmpFile)
1234 return TmpFile;
1235
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 std::string Error;
1237 const char *TmpDir = ::getenv("TMPDIR");
1238 if (!TmpDir)
1239 TmpDir = ::getenv("TEMP");
1240 if (!TmpDir)
1241 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001242#ifdef LLVM_ON_WIN32
1243 if (!TmpDir)
1244 TmpDir = ::getenv("USERPROFILE");
1245#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 if (!TmpDir)
1247 TmpDir = "/tmp";
1248 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001249 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001250 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001251 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001252 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 return std::string();
1254
Douglas Gregor44c181a2010-07-23 00:33:23 +00001255 return P.str();
1256}
1257
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001258/// \brief Compute the preamble for the main file, providing the source buffer
1259/// that corresponds to the main file along with a pair (bytes, start-of-line)
1260/// that describes the preamble.
1261std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001262ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1263 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001265 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001266 CreatedBuffer = false;
1267
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 // Try to determine if the main file has been remapped, either from the
1269 // command line (to another file) or directly through the compiler invocation
1270 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001271 llvm::MemoryBuffer *Buffer = 0;
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001272 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001273 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1274 // Check whether there is a file-file remapping of the main file
1275 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 M = PreprocessorOpts.remapped_file_begin(),
1277 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001278 M != E;
1279 ++M) {
1280 llvm::sys::PathWithStatus MPath(M->first);
1281 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1282 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1283 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001284 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001285 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001286 CreatedBuffer = false;
1287 }
1288
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001289 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001291 return std::make_pair((llvm::MemoryBuffer*)0,
1292 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001293 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001294 }
1295 }
1296 }
1297
1298 // Check whether there is a file-buffer remapping. It supercedes the
1299 // file-file remapping.
1300 for (PreprocessorOptions::remapped_file_buffer_iterator
1301 M = PreprocessorOpts.remapped_file_buffer_begin(),
1302 E = PreprocessorOpts.remapped_file_buffer_end();
1303 M != E;
1304 ++M) {
1305 llvm::sys::PathWithStatus MPath(M->first);
1306 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1307 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1308 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001309 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001310 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001311 CreatedBuffer = false;
1312 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001313
Douglas Gregor175c4a92010-07-23 23:58:40 +00001314 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001315 }
1316 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001318 }
1319
1320 // If the main source file was not remapped, load it now.
1321 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001322 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001323 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001324 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001325
1326 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001327 }
1328
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001329 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001330 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001331 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001332}
1333
Douglas Gregor754f3492010-07-24 00:38:13 +00001334static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001335 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001336 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001337 llvm::MemoryBuffer *Result
1338 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1339 memcpy(const_cast<char*>(Result->getBufferStart()),
1340 Old->getBufferStart(), Old->getBufferSize());
1341 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001342 ' ', NewSize - Old->getBufferSize() - 1);
1343 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001344
Douglas Gregor754f3492010-07-24 00:38:13 +00001345 return Result;
1346}
1347
Douglas Gregor175c4a92010-07-23 23:58:40 +00001348/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1349/// the source file.
1350///
1351/// This routine will compute the preamble of the main source file. If a
1352/// non-trivial preamble is found, it will precompile that preamble into a
1353/// precompiled header so that the precompiled preamble can be used to reduce
1354/// reparsing time. If a precompiled preamble has already been constructed,
1355/// this routine will determine if it is still valid and, if so, avoid
1356/// rebuilding the precompiled preamble.
1357///
Douglas Gregordf95a132010-08-09 20:45:32 +00001358/// \param AllowRebuild When true (the default), this routine is
1359/// allowed to rebuild the precompiled preamble if it is found to be
1360/// out-of-date.
1361///
1362/// \param MaxLines When non-zero, the maximum number of lines that
1363/// can occur within the preamble.
1364///
Douglas Gregor754f3492010-07-24 00:38:13 +00001365/// \returns If the precompiled preamble can be used, returns a newly-allocated
1366/// buffer that should be used in place of the main file when doing so.
1367/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001368llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001369 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001370 bool AllowRebuild,
1371 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001372
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001373 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001374 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1375 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001376 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001377 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001378
1379 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001380 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001381 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001382
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001383 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001384 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001385 if (CreatedPreambleBuffer)
1386 OwnedPreambleBuffer.reset(NewPreamble.first);
1387
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001388 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001389 // We couldn't find a preamble in the main source. Clear out the current
1390 // preamble, if we have one. It's obviously no good any more.
1391 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001392 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001393
1394 // The next time we actually see a preamble, precompile it.
1395 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001396 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001397 }
1398
1399 if (!Preamble.empty()) {
1400 // We've previously computed a preamble. Check whether we have the same
1401 // preamble now that we did before, and that there's enough space in
1402 // the main-file buffer within the precompiled preamble to fit the
1403 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001404 if (Preamble.size() == NewPreamble.second.first &&
1405 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001406 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001407 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001408 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001409 // The preamble has not changed. We may be able to re-use the precompiled
1410 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001411
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001412 // Check that none of the files used by the preamble have changed.
1413 bool AnyFileChanged = false;
1414
1415 // First, make a record of those files that have been overridden via
1416 // remapping or unsaved_files.
1417 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1418 for (PreprocessorOptions::remapped_file_iterator
1419 R = PreprocessorOpts.remapped_file_begin(),
1420 REnd = PreprocessorOpts.remapped_file_end();
1421 !AnyFileChanged && R != REnd;
1422 ++R) {
1423 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001424 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001425 // If we can't stat the file we're remapping to, assume that something
1426 // horrible happened.
1427 AnyFileChanged = true;
1428 break;
1429 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001430
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001431 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1432 StatBuf.st_mtime);
1433 }
1434 for (PreprocessorOptions::remapped_file_buffer_iterator
1435 R = PreprocessorOpts.remapped_file_buffer_begin(),
1436 REnd = PreprocessorOpts.remapped_file_buffer_end();
1437 !AnyFileChanged && R != REnd;
1438 ++R) {
1439 // FIXME: Should we actually compare the contents of file->buffer
1440 // remappings?
1441 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1442 0);
1443 }
1444
1445 // Check whether anything has changed.
1446 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1447 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1448 !AnyFileChanged && F != FEnd;
1449 ++F) {
1450 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1451 = OverriddenFiles.find(F->first());
1452 if (Overridden != OverriddenFiles.end()) {
1453 // This file was remapped; check whether the newly-mapped file
1454 // matches up with the previous mapping.
1455 if (Overridden->second != F->second)
1456 AnyFileChanged = true;
1457 continue;
1458 }
1459
1460 // The file was not remapped; check whether it has changed on disk.
1461 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001462 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001463 // If we can't stat the file, assume that something horrible happened.
1464 AnyFileChanged = true;
1465 } else if (StatBuf.st_size != F->second.first ||
1466 StatBuf.st_mtime != F->second.second)
1467 AnyFileChanged = true;
1468 }
1469
1470 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001471 // Okay! We can re-use the precompiled preamble.
1472
1473 // Set the state of the diagnostic object to mimic its state
1474 // after parsing the preamble.
1475 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001476 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001477 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001478 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001479
1480 // Create a version of the main file buffer that is padded to
1481 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001482 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001483 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001484 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001485 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001486 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001487
1488 // If we aren't allowed to rebuild the precompiled preamble, just
1489 // return now.
1490 if (!AllowRebuild)
1491 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001492
Douglas Gregor175c4a92010-07-23 23:58:40 +00001493 // We can't reuse the previously-computed preamble. Build a new one.
1494 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001495 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001496 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001497 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001498 } else if (!AllowRebuild) {
1499 // We aren't allowed to rebuild the precompiled preamble; just
1500 // return now.
1501 return 0;
1502 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001503
1504 // If the preamble rebuild counter > 1, it's because we previously
1505 // failed to build a preamble and we're not yet ready to try
1506 // again. Decrement the counter and return a failure.
1507 if (PreambleRebuildCounter > 1) {
1508 --PreambleRebuildCounter;
1509 return 0;
1510 }
1511
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001512 // Create a temporary file for the precompiled preamble. In rare
1513 // circumstances, this can fail.
1514 std::string PreamblePCHPath = GetPreamblePCHPath();
1515 if (PreamblePCHPath.empty()) {
1516 // Try again next time.
1517 PreambleRebuildCounter = 1;
1518 return 0;
1519 }
1520
Douglas Gregor175c4a92010-07-23 23:58:40 +00001521 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001522 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001523 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524
1525 // Create a new buffer that stores the preamble. The buffer also contains
1526 // extra space for the original contents of the file (which will be present
1527 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001528 // grows.
1529 PreambleReservedSize = NewPreamble.first->getBufferSize();
1530 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001531 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001532 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001533 PreambleReservedSize *= 2;
1534
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001535 // Save the preamble text for later; we'll need to compare against it for
1536 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001537 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001538 Preamble.assign(FileMgr->getFile(MainFilename),
1539 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001540 NewPreamble.first->getBufferStart()
1541 + NewPreamble.second.first);
1542 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1543
Douglas Gregor671947b2010-08-19 01:33:06 +00001544 delete PreambleBuffer;
1545 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001546 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001547 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001549 NewPreamble.first->getBufferStart(), Preamble.size());
1550 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001551 ' ', PreambleReservedSize - Preamble.size() - 1);
1552 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001553
1554 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001555 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1557
1558 // Tell the compiler invocation to generate a temporary precompiled header.
1559 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001560 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001561 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001562 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1563 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564
1565 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001566 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001567
1568 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001569 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1570 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001571
Douglas Gregor01b6e312011-07-01 18:22:13 +00001572 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001573 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001574
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001575 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001576 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001577
1578 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001579 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001580 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001581 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001582 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1583 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001584 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001585 PreprocessorOpts.eraseRemappedFile(
1586 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001587 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588 }
1589
1590 // Inform the target of the language options.
1591 //
1592 // FIXME: We shouldn't need to do this, the target should be immutable once
1593 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001594 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001595
Ted Kremenek03201fb2011-03-21 18:40:07 +00001596 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001597 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001598 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001599 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001600 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001601 "IR inputs not support here!");
1602
1603 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001604 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001605 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001606 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001607 TopLevelDecls.clear();
1608 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001609
1610 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001611 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001612
1613 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001614 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001615 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001616
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001617 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001618 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001619 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001620 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1621 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001622 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001623 PreprocessorOpts.eraseRemappedFile(
1624 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001625 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001626 }
1627
1628 Act->Execute();
1629 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001630
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001631 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001632 // There were errors parsing the preamble, so no precompiled header was
1633 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001634 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001635 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1636 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001637 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001638 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001639 PreprocessorOpts.eraseRemappedFile(
1640 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001641 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001642 }
1643
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001644 // Transfer any diagnostics generated when parsing the preamble into the set
1645 // of preamble diagnostics.
1646 PreambleDiagnostics.clear();
1647 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001648 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001649 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001650
Douglas Gregor175c4a92010-07-23 23:58:40 +00001651 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001652 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001653 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001654
1655 // Keep track of all of the files that the source manager knows about,
1656 // so we can verify whether they have changed or not.
1657 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001658 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001659 const llvm::MemoryBuffer *MainFileBuffer
1660 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1661 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1662 FEnd = SourceMgr.fileinfo_end();
1663 F != FEnd;
1664 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001665 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001666 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1667 continue;
1668
1669 FilesInPreamble[File->getName()]
1670 = std::make_pair(F->second->getSize(), File->getModificationTime());
1671 }
1672
Douglas Gregoreababfb2010-08-04 05:53:38 +00001673 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001674 PreprocessorOpts.eraseRemappedFile(
1675 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001676
1677 // If the hash of top-level entities differs from the hash of the top-level
1678 // entities the last time we rebuilt the preamble, clear out the completion
1679 // cache.
1680 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1681 CompletionCacheTopLevelHashValue = 0;
1682 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1683 }
1684
Douglas Gregor754f3492010-07-24 00:38:13 +00001685 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001686 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001687 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001688}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001689
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001690void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1691 std::vector<Decl *> Resolved;
1692 Resolved.reserve(TopLevelDeclsInPreamble.size());
1693 ExternalASTSource &Source = *getASTContext().getExternalSource();
1694 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1695 // Resolve the declaration ID to an actual declaration, possibly
1696 // deserializing the declaration in the process.
1697 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1698 if (D)
1699 Resolved.push_back(D);
1700 }
1701 TopLevelDeclsInPreamble.clear();
1702 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1703}
1704
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001705void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1706 // Steal the created target, context, and preprocessor.
1707 TheSema.reset(CI.takeSema());
1708 Consumer.reset(CI.takeASTConsumer());
1709 Ctx = &CI.getASTContext();
1710 PP = &CI.getPreprocessor();
1711 CI.setSourceManager(0);
1712 CI.setFileManager(0);
1713 Target = &CI.getTarget();
1714 Reader = CI.getModuleManager();
1715}
1716
Chris Lattner5f9e2722011-07-23 10:55:15 +00001717StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001718 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1719 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1720 if (Input.isFile())
1721 return Input.getFile();
1722 else
1723 return Input.getBuffer()->getBufferIdentifier();
1724 }
1725
1726 if (SourceMgr) {
1727 if (const FileEntry *
1728 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1729 return FE->getName();
1730 }
1731
1732 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001733}
1734
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001735StringRef ASTUnit::getASTFileName() const {
1736 if (!isMainFileAST())
1737 return StringRef();
1738
1739 serialization::ModuleFile &
1740 Mod = Reader->getModuleManager().getPrimaryModule();
1741 return Mod.FileName;
1742}
1743
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001744ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001745 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001746 bool CaptureDiagnostics,
1747 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001748 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001749 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001750 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001751 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001752 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001753 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001754 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001755 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1756 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1757 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001758
1759 return AST.take();
1760}
1761
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001762ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001763 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001764 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001765 ASTUnit *Unit,
1766 bool Persistent,
1767 StringRef ResourceFilesPath,
1768 bool OnlyLocalDecls,
1769 bool CaptureDiagnostics,
1770 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001771 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001772 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001773 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001774 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001775 assert(CI && "A CompilerInvocation is required");
1776
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001777 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001778 ASTUnit *AST = Unit;
1779 if (!AST) {
1780 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001781 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001782 AST = OwnAST.get();
1783 }
1784
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001785 if (!ResourceFilesPath.empty()) {
1786 // Override the resources path.
1787 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1788 }
1789 AST->OnlyLocalDecls = OnlyLocalDecls;
1790 AST->CaptureDiagnostics = CaptureDiagnostics;
1791 if (PrecompilePreamble)
1792 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001793 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001794 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001795 AST->IncludeBriefCommentsInCodeCompletion
1796 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001797
1798 // Recover resources if we crash before exiting this method.
1799 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001800 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001801 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1802 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001803 DiagCleanup(Diags.getPtr());
1804
1805 // We'll manage file buffers ourselves.
1806 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1807 CI->getFrontendOpts().DisableFree = false;
1808 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1809
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001810 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001811 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001812
1813 // Recover resources if we crash before exiting this method.
1814 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1815 CICleanup(Clang.get());
1816
1817 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001818 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001819
1820 // Set up diagnostics, capturing any diagnostics that would
1821 // otherwise be dropped.
1822 Clang->setDiagnostics(&AST->getDiagnostics());
1823
1824 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001825 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001826 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001827 if (!Clang->hasTarget())
1828 return 0;
1829
1830 // Inform the target of the language options.
1831 //
1832 // FIXME: We shouldn't need to do this, the target should be immutable once
1833 // created. This complexity should be lifted elsewhere.
1834 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1835
1836 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1837 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001838 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001839 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001840 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001841 "IR inputs not supported here!");
1842
1843 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001844 AST->TheSema.reset();
1845 AST->Ctx = 0;
1846 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001847 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001848
1849 // Create a file manager object to provide access to and cache the filesystem.
1850 Clang->setFileManager(&AST->getFileManager());
1851
1852 // Create the source manager.
1853 Clang->setSourceManager(&AST->getSourceManager());
1854
1855 ASTFrontendAction *Act = Action;
1856
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001857 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001858 if (!Act) {
1859 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1860 Act = TrackerAct.get();
1861 }
1862
1863 // Recover resources if we crash before exiting this method.
1864 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1865 ActCleanup(TrackerAct.get());
1866
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001867 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1868 AST->transferASTDataFromCompilerInstance(*Clang);
1869 if (OwnAST && ErrAST)
1870 ErrAST->swap(OwnAST);
1871
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001872 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001873 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001874
1875 if (Persistent && !TrackerAct) {
1876 Clang->getPreprocessor().addPPCallbacks(
1877 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1878 std::vector<ASTConsumer*> Consumers;
1879 if (Clang->hasASTConsumer())
1880 Consumers.push_back(Clang->takeASTConsumer());
1881 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1882 AST->getCurrentTopLevelHashValue()));
1883 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1884 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001885 if (!Act->Execute()) {
1886 AST->transferASTDataFromCompilerInstance(*Clang);
1887 if (OwnAST && ErrAST)
1888 ErrAST->swap(OwnAST);
1889
1890 return 0;
1891 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001892
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001893 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001894 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001895
1896 Act->EndSourceFile();
1897
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001898 if (OwnAST)
1899 return OwnAST.take();
1900 else
1901 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001902}
1903
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001904bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1905 if (!Invocation)
1906 return true;
1907
1908 // We'll manage file buffers ourselves.
1909 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1910 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001911 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001912
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001914 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001915 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001916 OverrideMainBuffer
1917 = getMainBufferWithPrecompiledPreamble(*Invocation);
1918 }
1919
Douglas Gregor213f18b2010-10-28 15:44:59 +00001920 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001921 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001922
Ted Kremenek25a11e12011-03-22 01:15:24 +00001923 // Recover resources if we crash before exiting this method.
1924 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1925 MemBufferCleanup(OverrideMainBuffer);
1926
Douglas Gregor213f18b2010-10-28 15:44:59 +00001927 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001928}
1929
Douglas Gregorabc563f2010-07-19 21:46:24 +00001930ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001931 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001932 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001933 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001934 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001935 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001936 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001937 bool IncludeBriefCommentsInCodeCompletion,
1938 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001939 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001940 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001941 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001942 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001943 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001944 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001945 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001946 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001947 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001948 AST->IncludeBriefCommentsInCodeCompletion
1949 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001950 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001951 AST->FileSystemOpts = CI->getFileSystemOpts();
1952 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001953 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001954
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001955 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001956 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1957 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001958 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1959 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001960 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001961
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001962 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001963}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001964
1965ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1966 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001967 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001968 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001969 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001970 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001971 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001972 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001973 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001974 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001975 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001976 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001977 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001978 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001979 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001980 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001981 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001982 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001983 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001984 // No diagnostics engine was provided, so create our own diagnostics object
1985 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001986 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001987 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001988
Chris Lattner5f9e2722011-07-23 10:55:15 +00001989 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001990
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001991 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001992
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001993 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001994
Douglas Gregore47be3e2010-11-11 00:39:14 +00001995 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001996 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001997
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001998 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001999 llvm::makeArrayRef(ArgBegin, ArgEnd),
2000 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00002001 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00002002 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002003 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00002004
Douglas Gregor4db64a42010-01-23 00:14:00 +00002005 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002006 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2007 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2008 if (const llvm::MemoryBuffer *
2009 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2010 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2011 } else {
2012 const char *fname = fileOrBuf.get<const char *>();
2013 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2014 }
2015 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002016 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2017 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2018 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002019
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002020 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002021 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002022
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002023 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2024
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002025 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002026 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002027 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002028 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002029 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002030 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002031 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002032 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002033 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002034 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002035 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002036 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002037 AST->IncludeBriefCommentsInCodeCompletion
2038 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002039 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002040 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002041 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002042 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002043 if (ForSerialization)
2044 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002045 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002046
2047 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002048 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2049 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002050
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002051 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2052 // Some error occurred, if caller wants to examine diagnostics, pass it the
2053 // ASTUnit.
2054 if (ErrAST) {
2055 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2056 ErrAST->swap(AST);
2057 }
2058 return 0;
2059 }
2060
2061 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002062}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002063
2064bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002065 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002066 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002067
2068 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002069
Douglas Gregor213f18b2010-10-28 15:44:59 +00002070 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002071 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002072
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002073 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002074 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2075 for (PreprocessorOptions::remapped_file_buffer_iterator
2076 R = PPOpts.remapped_file_buffer_begin(),
2077 REnd = PPOpts.remapped_file_buffer_end();
2078 R != REnd;
2079 ++R) {
2080 delete R->second;
2081 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002082 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002083 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2084 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2085 if (const llvm::MemoryBuffer *
2086 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2087 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2088 memBuf);
2089 } else {
2090 const char *fname = fileOrBuf.get<const char *>();
2091 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2092 fname);
2093 }
2094 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002095
Douglas Gregoreababfb2010-08-04 05:53:38 +00002096 // If we have a preamble file lying around, or if we might try to
2097 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002098 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002099 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002100 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002101
Douglas Gregorabc563f2010-07-19 21:46:24 +00002102 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002103 getDiagnostics().Reset();
2104 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002105 if (OverrideMainBuffer)
2106 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002107
Douglas Gregor175c4a92010-07-23 23:58:40 +00002108 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002109 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002110
2111 // If we're caching global code-completion results, and the top-level
2112 // declarations have changed, clear out the code-completion cache.
2113 if (!Result && ShouldCacheCodeCompletionResults &&
2114 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2115 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002116
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002117 // We now need to clear out the completion info related to this translation
2118 // unit; it'll be recreated if necessary.
2119 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002120
Douglas Gregor175c4a92010-07-23 23:58:40 +00002121 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002122}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002123
Douglas Gregor87c08a52010-08-13 22:48:40 +00002124//----------------------------------------------------------------------------//
2125// Code completion
2126//----------------------------------------------------------------------------//
2127
2128namespace {
2129 /// \brief Code completion consumer that combines the cached code-completion
2130 /// results from an ASTUnit with the code-completion results provided to it,
2131 /// then passes the result on to
2132 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002133 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002134 ASTUnit &AST;
2135 CodeCompleteConsumer &Next;
2136
2137 public:
2138 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002139 const CodeCompleteOptions &CodeCompleteOpts)
2140 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2141 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002142 {
2143 // Compute the set of contexts in which we will look when we don't have
2144 // any information about the specific context.
2145 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002146 = (1LL << CodeCompletionContext::CCC_TopLevel)
2147 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2148 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2149 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2150 | (1LL << CodeCompletionContext::CCC_Statement)
2151 | (1LL << CodeCompletionContext::CCC_Expression)
2152 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2153 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2154 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2155 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2156 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2157 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2158 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002159
David Blaikie4e4d0842012-03-11 07:00:24 +00002160 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002161 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2162 | (1LL << CodeCompletionContext::CCC_UnionTag)
2163 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002164 }
2165
2166 virtual void ProcessCodeCompleteResults(Sema &S,
2167 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002168 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002169 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170
2171 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2172 OverloadCandidate *Candidates,
2173 unsigned NumCandidates) {
2174 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2175 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002176
Douglas Gregordae68752011-02-01 22:57:45 +00002177 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002178 return Next.getAllocator();
2179 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002180
2181 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2182 return Next.getCodeCompletionTUInfo();
2183 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002184 };
2185}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002186
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187/// \brief Helper function that computes which global names are hidden by the
2188/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002189static void CalculateHiddenNames(const CodeCompletionContext &Context,
2190 CodeCompletionResult *Results,
2191 unsigned NumResults,
2192 ASTContext &Ctx,
2193 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002194 bool OnlyTagNames = false;
2195 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002196 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197 case CodeCompletionContext::CCC_TopLevel:
2198 case CodeCompletionContext::CCC_ObjCInterface:
2199 case CodeCompletionContext::CCC_ObjCImplementation:
2200 case CodeCompletionContext::CCC_ObjCIvarList:
2201 case CodeCompletionContext::CCC_ClassStructUnion:
2202 case CodeCompletionContext::CCC_Statement:
2203 case CodeCompletionContext::CCC_Expression:
2204 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002205 case CodeCompletionContext::CCC_DotMemberAccess:
2206 case CodeCompletionContext::CCC_ArrowMemberAccess:
2207 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002208 case CodeCompletionContext::CCC_Namespace:
2209 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002210 case CodeCompletionContext::CCC_Name:
2211 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002212 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002213 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002214 break;
2215
2216 case CodeCompletionContext::CCC_EnumTag:
2217 case CodeCompletionContext::CCC_UnionTag:
2218 case CodeCompletionContext::CCC_ClassOrStructTag:
2219 OnlyTagNames = true;
2220 break;
2221
2222 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002223 case CodeCompletionContext::CCC_MacroName:
2224 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002225 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002226 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002227 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002228 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002229 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002230 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002231 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002232 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2233 case CodeCompletionContext::CCC_ObjCClassMessage:
2234 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002235 // We're looking for nothing, or we're looking for names that cannot
2236 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002237 return;
2238 }
2239
John McCall0a2c5e22010-08-25 06:19:51 +00002240 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002241 for (unsigned I = 0; I != NumResults; ++I) {
2242 if (Results[I].Kind != Result::RK_Declaration)
2243 continue;
2244
2245 unsigned IDNS
2246 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2247
2248 bool Hiding = false;
2249 if (OnlyTagNames)
2250 Hiding = (IDNS & Decl::IDNS_Tag);
2251 else {
2252 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002253 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2254 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002255 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002256 HiddenIDNS |= Decl::IDNS_Tag;
2257 Hiding = (IDNS & HiddenIDNS);
2258 }
2259
2260 if (!Hiding)
2261 continue;
2262
2263 DeclarationName Name = Results[I].Declaration->getDeclName();
2264 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2265 HiddenNames.insert(Identifier->getName());
2266 else
2267 HiddenNames.insert(Name.getAsString());
2268 }
2269}
2270
2271
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002272void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2273 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002274 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275 unsigned NumResults) {
2276 // Merge the results we were given with the results we cached.
2277 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002278 uint64_t InContexts =
2279 Context.getKind() == CodeCompletionContext::CCC_Recovery
2280 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002281 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002282 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002283 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002284 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002285 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002286 C = AST.cached_completion_begin(),
2287 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002288 C != CEnd; ++C) {
2289 // If the context we are in matches any of the contexts we are
2290 // interested in, we'll add this result.
2291 if ((C->ShowInContexts & InContexts) == 0)
2292 continue;
2293
2294 // If we haven't added any results previously, do so now.
2295 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002296 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2297 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002298 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2299 AddedResult = true;
2300 }
2301
Douglas Gregor5f808c22010-08-16 21:18:39 +00002302 // Determine whether this global completion result is hidden by a local
2303 // completion result. If so, skip it.
2304 if (C->Kind != CXCursor_MacroDefinition &&
2305 HiddenNames.count(C->Completion->getTypedText()))
2306 continue;
2307
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002308 // Adjust priority based on similar type classes.
2309 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002310 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002311 if (!Context.getPreferredType().isNull()) {
2312 if (C->Kind == CXCursor_MacroDefinition) {
2313 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002314 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002315 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002316 } else if (C->Type) {
2317 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002318 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002319 Context.getPreferredType().getUnqualifiedType());
2320 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2321 if (ExpectedSTC == C->TypeClass) {
2322 // We know this type is similar; check for an exact match.
2323 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002324 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002325 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002326 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002327 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2328 Priority /= CCF_ExactTypeMatch;
2329 else
2330 Priority /= CCF_SimilarTypeMatch;
2331 }
2332 }
2333 }
2334
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002335 // Adjust the completion string, if required.
2336 if (C->Kind == CXCursor_MacroDefinition &&
2337 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2338 // Create a new code-completion string that just contains the
2339 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002340 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2341 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002342 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002343 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002344 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002345 }
2346
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002347 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002348 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002349 }
2350
2351 // If we did not add any cached completion results, just forward the
2352 // results we were given to the next consumer.
2353 if (!AddedResult) {
2354 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2355 return;
2356 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002357
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002358 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2359 AllResults.size());
2360}
2361
2362
2363
Chris Lattner5f9e2722011-07-23 10:55:15 +00002364void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002365 RemappedFile *RemappedFiles,
2366 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002367 bool IncludeMacros,
2368 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002369 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002370 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002371 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002372 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002373 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2374 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002375 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002376 return;
2377
Douglas Gregor213f18b2010-10-28 15:44:59 +00002378 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002379 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002380 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002381
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002382 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002383 CCInvocation(new CompilerInvocation(*Invocation));
2384
2385 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002386 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002387 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002388
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002389 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2390 CachedCompletionResults.empty();
2391 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2392 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2393 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2394
2395 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2396
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397 FrontendOpts.CodeCompletionAt.FileName = File;
2398 FrontendOpts.CodeCompletionAt.Line = Line;
2399 FrontendOpts.CodeCompletionAt.Column = Column;
2400
2401 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002402 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002403
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002404 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002405
2406 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002407 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2408 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002409
Ted Kremenek4f327862011-03-21 18:40:17 +00002410 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002411 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412
2413 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002414 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002415 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002419
2420 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002421 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002422 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002423 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002424 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002425 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002426 }
2427
2428 // Inform the target of the language options.
2429 //
2430 // FIXME: We shouldn't need to do this, the target should be immutable once
2431 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002432 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002433
Ted Kremenek03201fb2011-03-21 18:40:07 +00002434 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002435 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002436 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002437 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002438 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002439 "IR inputs not support here!");
2440
2441
2442 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002443 Clang->setFileManager(&FileMgr);
2444 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002445
2446 // Remap files.
2447 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002448 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002449 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002450 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2451 if (const llvm::MemoryBuffer *
2452 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2453 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2454 OwnedBuffers.push_back(memBuf);
2455 } else {
2456 const char *fname = fileOrBuf.get<const char *>();
2457 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2458 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002459 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002460
Douglas Gregor87c08a52010-08-13 22:48:40 +00002461 // Use the code completion consumer we were given, but adding any cached
2462 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002463 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002464 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002465 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002466
Douglas Gregordf95a132010-08-09 20:45:32 +00002467 // If we have a precompiled preamble, try to use it. We only allow
2468 // the use of the precompiled preamble if we're if the completion
2469 // point is within the main file, after the end of the precompiled
2470 // preamble.
2471 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002472 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002473 using llvm::sys::FileStatus;
2474 llvm::sys::PathWithStatus CompleteFilePath(File);
2475 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2476 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2477 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002478 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2479 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002480 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002481 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002482 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002483 }
2484
2485 // If the main file has been overridden due to the use of a preamble,
2486 // make that override happen and introduce the preamble.
2487 if (OverrideMainBuffer) {
2488 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2489 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2490 PreprocessorOpts.PrecompiledPreambleBytes.second
2491 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002492 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002493 PreprocessorOpts.DisablePCHValidation = true;
2494
Douglas Gregor2283d792010-08-20 00:59:43 +00002495 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002496 } else {
2497 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2498 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002499 }
2500
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002501 // Disable the preprocessing record if modules are not enabled.
2502 if (!Clang->getLangOpts().Modules)
2503 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002504
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002505 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002506 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002507 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002508 Act->Execute();
2509 Act->EndSourceFile();
2510 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002511}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002512
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002513bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002514 // Write to a temporary file and later rename it to the actual file, to avoid
2515 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002516 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002517 TempPath = File;
2518 TempPath += "-%%%%%%%%";
2519 int fd;
2520 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2521 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002522 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002523
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002524 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2525 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002526 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002527
2528 serialize(Out);
2529 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002530 if (Out.has_error()) {
2531 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002532 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002533 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002534
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002535 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002536 bool exists;
2537 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002538 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002539 }
2540
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002541 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002542}
2543
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002544static bool serializeUnit(ASTWriter &Writer,
2545 SmallVectorImpl<char> &Buffer,
2546 Sema &S,
2547 bool hasErrors,
2548 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002549 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002550
2551 // Write the generated bitstream to "Out".
2552 if (!Buffer.empty())
2553 OS.write(Buffer.data(), Buffer.size());
2554
2555 return false;
2556}
2557
Chris Lattner5f9e2722011-07-23 10:55:15 +00002558bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002559 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002560
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002561 if (WriterData)
2562 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2563 getSema(), hasErrors, OS);
2564
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002565 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002566 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002567 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002568 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002569}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002570
2571typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2572
2573static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2574 unsigned Raw = L.getRawEncoding();
2575 const unsigned MacroBit = 1U << 31;
2576 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2577 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2578}
2579
2580void ASTUnit::TranslateStoredDiagnostics(
2581 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002584 const SmallVectorImpl<StoredDiagnostic> &Diags,
2585 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002586 // The stored diagnostic has the old source manager in it; update
2587 // the locations to refer into the new source manager. We also need to remap
2588 // all the locations to the new view. This includes the diag location, any
2589 // associated source ranges, and the source ranges of associated fix-its.
2590 // FIXME: There should be a cleaner way to do this.
2591
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002593 Result.reserve(Diags.size());
2594 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002595 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002596 assert(Mod && "Don't have preamble module");
2597 SLocRemap &Remap = Mod->SLocRemap;
2598 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2599 // Rebuild the StoredDiagnostic.
2600 const StoredDiagnostic &SD = Diags[I];
2601 SourceLocation L = SD.getLocation();
2602 TranslateSLoc(L, Remap);
2603 FullSourceLoc Loc(L, SrcMgr);
2604
Chris Lattner5f9e2722011-07-23 10:55:15 +00002605 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002606 Ranges.reserve(SD.range_size());
2607 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2608 E = SD.range_end();
2609 I != E; ++I) {
2610 SourceLocation BL = I->getBegin();
2611 TranslateSLoc(BL, Remap);
2612 SourceLocation EL = I->getEnd();
2613 TranslateSLoc(EL, Remap);
2614 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2615 }
2616
Chris Lattner5f9e2722011-07-23 10:55:15 +00002617 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002618 FixIts.reserve(SD.fixit_size());
2619 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2620 E = SD.fixit_end();
2621 I != E; ++I) {
2622 FixIts.push_back(FixItHint());
2623 FixItHint &FH = FixIts.back();
2624 FH.CodeToInsert = I->CodeToInsert;
2625 SourceLocation BL = I->RemoveRange.getBegin();
2626 TranslateSLoc(BL, Remap);
2627 SourceLocation EL = I->RemoveRange.getEnd();
2628 TranslateSLoc(EL, Remap);
2629 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2630 I->RemoveRange.isTokenRange());
2631 }
2632
2633 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2634 SD.getMessage(), Loc, Ranges, FixIts));
2635 }
2636 Result.swap(Out);
2637}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002638
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002639static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2640 std::pair<unsigned, Decl *> R) {
2641 return L.first < R.first;
2642}
2643
2644void ASTUnit::addFileLevelDecl(Decl *D) {
2645 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002646
2647 // We only care about local declarations.
2648 if (D->isFromASTFile())
2649 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002650
2651 SourceManager &SM = *SourceMgr;
2652 SourceLocation Loc = D->getLocation();
2653 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2654 return;
2655
2656 // We only keep track of the file-level declarations of each file.
2657 if (!D->getLexicalDeclContext()->isFileContext())
2658 return;
2659
2660 SourceLocation FileLoc = SM.getFileLoc(Loc);
2661 assert(SM.isLocalSourceLocation(FileLoc));
2662 FileID FID;
2663 unsigned Offset;
2664 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2665 if (FID.isInvalid())
2666 return;
2667
2668 LocDeclsTy *&Decls = FileDecls[FID];
2669 if (!Decls)
2670 Decls = new LocDeclsTy();
2671
2672 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2673
2674 if (Decls->empty() || Decls->back().first <= Offset) {
2675 Decls->push_back(LocDecl);
2676 return;
2677 }
2678
2679 LocDeclsTy::iterator
2680 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2681
2682 Decls->insert(I, LocDecl);
2683}
2684
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002685void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2686 SmallVectorImpl<Decl *> &Decls) {
2687 if (File.isInvalid())
2688 return;
2689
2690 if (SourceMgr->isLoadedFileID(File)) {
2691 assert(Ctx->getExternalSource() && "No external source!");
2692 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2693 Decls);
2694 }
2695
2696 FileDeclsTy::iterator I = FileDecls.find(File);
2697 if (I == FileDecls.end())
2698 return;
2699
2700 LocDeclsTy &LocDecls = *I->second;
2701 if (LocDecls.empty())
2702 return;
2703
2704 LocDeclsTy::iterator
2705 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2706 std::make_pair(Offset, (Decl*)0), compLocDecl);
2707 if (BeginIt != LocDecls.begin())
2708 --BeginIt;
2709
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002710 // If we are pointing at a top-level decl inside an objc container, we need
2711 // to backtrack until we find it otherwise we will fail to report that the
2712 // region overlaps with an objc container.
2713 while (BeginIt != LocDecls.begin() &&
2714 BeginIt->second->isTopLevelDeclInObjCContainer())
2715 --BeginIt;
2716
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002717 LocDeclsTy::iterator
2718 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2719 std::make_pair(Offset+Length, (Decl*)0),
2720 compLocDecl);
2721 if (EndIt != LocDecls.end())
2722 ++EndIt;
2723
2724 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2725 Decls.push_back(DIt->second);
2726}
2727
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002728SourceLocation ASTUnit::getLocation(const FileEntry *File,
2729 unsigned Line, unsigned Col) const {
2730 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002731 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002732 return SM.getMacroArgExpandedLocation(Loc);
2733}
2734
2735SourceLocation ASTUnit::getLocation(const FileEntry *File,
2736 unsigned Offset) const {
2737 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002738 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002739 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2740}
2741
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002742/// \brief If \arg Loc is a loaded location from the preamble, returns
2743/// the corresponding local location of the main file, otherwise it returns
2744/// \arg Loc.
2745SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2746 FileID PreambleID;
2747 if (SourceMgr)
2748 PreambleID = SourceMgr->getPreambleFileID();
2749
2750 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2751 return Loc;
2752
2753 unsigned Offs;
2754 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2755 SourceLocation FileLoc
2756 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2757 return FileLoc.getLocWithOffset(Offs);
2758 }
2759
2760 return Loc;
2761}
2762
2763/// \brief If \arg Loc is a local location of the main file but inside the
2764/// preamble chunk, returns the corresponding loaded location from the
2765/// preamble, otherwise it returns \arg Loc.
2766SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2767 FileID PreambleID;
2768 if (SourceMgr)
2769 PreambleID = SourceMgr->getPreambleFileID();
2770
2771 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2772 return Loc;
2773
2774 unsigned Offs;
2775 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2776 Offs < Preamble.size()) {
2777 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2778 return FileLoc.getLocWithOffset(Offs);
2779 }
2780
2781 return Loc;
2782}
2783
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002784bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2785 FileID FID;
2786 if (SourceMgr)
2787 FID = SourceMgr->getPreambleFileID();
2788
2789 if (Loc.isInvalid() || FID.isInvalid())
2790 return false;
2791
2792 return SourceMgr->isInFileID(Loc, FID);
2793}
2794
2795bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2796 FileID FID;
2797 if (SourceMgr)
2798 FID = SourceMgr->getMainFileID();
2799
2800 if (Loc.isInvalid() || FID.isInvalid())
2801 return false;
2802
2803 return SourceMgr->isInFileID(Loc, FID);
2804}
2805
2806SourceLocation ASTUnit::getEndOfPreambleFileID() {
2807 FileID FID;
2808 if (SourceMgr)
2809 FID = SourceMgr->getPreambleFileID();
2810
2811 if (FID.isInvalid())
2812 return SourceLocation();
2813
2814 return SourceMgr->getLocForEndOfFile(FID);
2815}
2816
2817SourceLocation ASTUnit::getStartOfMainFileID() {
2818 FileID FID;
2819 if (SourceMgr)
2820 FID = SourceMgr->getMainFileID();
2821
2822 if (FID.isInvalid())
2823 return SourceLocation();
2824
2825 return SourceMgr->getLocForStartOfFile(FID);
2826}
2827
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002828std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2829ASTUnit::getLocalPreprocessingEntities() const {
2830 if (isMainFileAST()) {
2831 serialization::ModuleFile &
2832 Mod = Reader->getModuleManager().getPrimaryModule();
2833 return Reader->getModulePreprocessedEntities(Mod);
2834 }
2835
2836 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2837 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2838
2839 return std::make_pair(PreprocessingRecord::iterator(),
2840 PreprocessingRecord::iterator());
2841}
2842
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002843bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002844 if (isMainFileAST()) {
2845 serialization::ModuleFile &
2846 Mod = Reader->getModuleManager().getPrimaryModule();
2847 ASTReader::ModuleDeclIterator MDI, MDE;
2848 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2849 for (; MDI != MDE; ++MDI) {
2850 if (!Fn(context, *MDI))
2851 return false;
2852 }
2853
2854 return true;
2855 }
2856
2857 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2858 TLEnd = top_level_end();
2859 TL != TLEnd; ++TL) {
2860 if (!Fn(context, *TL))
2861 return false;
2862 }
2863
2864 return true;
2865}
2866
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002867namespace {
2868struct PCHLocatorInfo {
2869 serialization::ModuleFile *Mod;
2870 PCHLocatorInfo() : Mod(0) {}
2871};
2872}
2873
2874static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2875 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2876 switch (M.Kind) {
2877 case serialization::MK_Module:
2878 return true; // skip dependencies.
2879 case serialization::MK_PCH:
2880 Info.Mod = &M;
2881 return true; // found it.
2882 case serialization::MK_Preamble:
2883 return false; // look in dependencies.
2884 case serialization::MK_MainFile:
2885 return false; // look in dependencies.
2886 }
2887
2888 return true;
2889}
2890
2891const FileEntry *ASTUnit::getPCHFile() {
2892 if (!Reader)
2893 return 0;
2894
2895 PCHLocatorInfo Info;
2896 Reader->getModuleManager().visit(PCHLocator, &Info);
2897 if (Info.Mod)
2898 return Info.Mod->File;
2899
2900 return 0;
2901}
2902
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002903bool ASTUnit::isModuleFile() {
2904 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2905}
2906
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002907void ASTUnit::PreambleData::countLines() const {
2908 NumLines = 0;
2909 if (empty())
2910 return;
2911
2912 for (std::vector<char>::const_iterator
2913 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2914 if (*I == '\n')
2915 ++NumLines;
2916 }
2917 if (Buffer.back() != '\n')
2918 ++NumLines;
2919}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002920
2921#ifndef NDEBUG
2922ASTUnit::ConcurrencyState::ConcurrencyState() {
2923 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2924}
2925
2926ASTUnit::ConcurrencyState::~ConcurrencyState() {
2927 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2928}
2929
2930void ASTUnit::ConcurrencyState::start() {
2931 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2932 assert(acquired && "Concurrent access to ASTUnit!");
2933}
2934
2935void ASTUnit::ConcurrencyState::finish() {
2936 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2937}
2938
2939#else // NDEBUG
2940
2941ASTUnit::ConcurrencyState::ConcurrencyState() {}
2942ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2943void ASTUnit::ConcurrencyState::start() {}
2944void ASTUnit::ConcurrencyState::finish() {}
2945
2946#endif