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