blob: 0463db18dc069fea94554915d262cab198e87e26 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-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 Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000033#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000034#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000035#include "llvm/System/Path.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000036#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000037#include <cstdio>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000038using namespace clang;
39
Douglas Gregord03e8232010-04-05 21:10:19 +000040ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000041 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
42 ConcurrencyCheckValue(CheckUnlocked) { }
Douglas Gregord03e8232010-04-05 21:10:19 +000043
Daniel Dunbar764c0822009-12-01 09:51:01 +000044ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000045 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000046 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000047 if (!PreambleFile.empty())
48 PreambleFile.eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000049
50 // Free the buffers associated with remapped files. We are required to
51 // perform this operation here because we explicitly request that the
52 // compiler instance *not* free these buffers for each invocation of the
53 // parser.
54 if (Invocation.get()) {
55 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
56 for (PreprocessorOptions::remapped_file_buffer_iterator
57 FB = PPOpts.remapped_file_buffer_begin(),
58 FBEnd = PPOpts.remapped_file_buffer_end();
59 FB != FBEnd;
60 ++FB)
61 delete FB->second;
62 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +000063}
64
65void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000066 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
67 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000068 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000069}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000070
71namespace {
72
73/// \brief Gathers information from PCHReader that will be used to initialize
74/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +000075class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000076 LangOptions &LangOpt;
77 HeaderSearch &HSI;
78 std::string &TargetTriple;
79 std::string &Predefines;
80 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +000081
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000082 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +000083
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000084public:
85 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
86 std::string &TargetTriple, std::string &Predefines,
87 unsigned &Counter)
88 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
89 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +000090
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000091 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
92 LangOpt = LangOpts;
93 return false;
94 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Daniel Dunbar20a682d2009-11-11 00:52:11 +000096 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000097 TargetTriple = Triple;
98 return false;
99 }
Mike Stump11289f42009-09-09 15:08:12 +0000100
Sebastian Redl8b41f302010-07-14 23:29:55 +0000101 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000102 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000103 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000104 Predefines = Buffers[0].Data;
105 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
106 Predefines += Buffers[I].Data;
107 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000108 return false;
109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Douglas Gregora2f49452010-03-16 19:09:18 +0000111 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000112 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000115 virtual void ReadCounter(unsigned Value) {
116 Counter = Value;
117 }
118};
119
Douglas Gregor33cdd812010-02-18 18:08:43 +0000120class StoredDiagnosticClient : public DiagnosticClient {
121 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
122
123public:
124 explicit StoredDiagnosticClient(
125 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
126 : StoredDiags(StoredDiags) { }
127
128 virtual void HandleDiagnostic(Diagnostic::Level Level,
129 const DiagnosticInfo &Info);
130};
131
132/// \brief RAII object that optionally captures diagnostics, if
133/// there is no diagnostic client to capture them already.
134class CaptureDroppedDiagnostics {
135 Diagnostic &Diags;
136 StoredDiagnosticClient Client;
137 DiagnosticClient *PreviousClient;
138
139public:
140 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
141 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
142 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
143 {
144 if (RequestCapture || Diags.getClient() == 0)
145 Diags.setClient(&Client);
146 }
147
148 ~CaptureDroppedDiagnostics() {
149 Diags.setClient(PreviousClient);
150 }
151};
152
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000153} // anonymous namespace
154
Douglas Gregor33cdd812010-02-18 18:08:43 +0000155void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
156 const DiagnosticInfo &Info) {
157 StoredDiags.push_back(StoredDiagnostic(Level, Info));
158}
159
Steve Naroffc0683b92009-09-03 18:19:54 +0000160const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000161 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000162}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000163
Steve Naroff44cd60e2009-10-15 22:23:48 +0000164const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbara18f9582009-12-02 21:47:43 +0000165 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer2ecf8eb2010-01-30 16:23:25 +0000166 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000167}
168
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000169ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000170 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000171 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000172 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000173 unsigned NumRemappedFiles,
174 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000175 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
176
Douglas Gregor7f95d262010-04-05 23:52:57 +0000177 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000178 // No diagnostics engine was provided, so create our own diagnostics object
179 // with the default options.
180 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000181 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000182 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000183
184 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000185 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000186 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000187 AST->FileMgr.reset(new FileManager);
188 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000189 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000190
Douglas Gregor33cdd812010-02-18 18:08:43 +0000191 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000192 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000193 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000194
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000195 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
196 // Create the file entry for the file that we're mapping from.
197 const FileEntry *FromFile
198 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
199 RemappedFiles[I].second->getBufferSize(),
200 0);
201 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000202 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000203 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000204 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000205 continue;
206 }
207
208 // Override the contents of the "from" file with the contents of
209 // the "to" file.
210 AST->getSourceManager().overrideFileContents(FromFile,
211 RemappedFiles[I].second);
212 }
213
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000214 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000215
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000216 LangOptions LangInfo;
217 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
218 std::string TargetTriple;
219 std::string Predefines;
220 unsigned Counter;
221
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000222 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000223 llvm::OwningPtr<ExternalASTSource> Source;
224
Ted Kremenek428c6372009-10-19 21:44:57 +0000225 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000226 AST->getDiagnostics()));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000227 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
228 Predefines, Counter));
229
230 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000231 case PCHReader::Success:
232 break;
Mike Stump11289f42009-09-09 15:08:12 +0000233
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000234 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000235 case PCHReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000236 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000237 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Daniel Dunbara8a50932009-12-02 08:44:16 +0000240 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
241
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000242 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000243
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000244 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000245 //
246 // FIXME: This is broken, we should store the TargetOptions in the PCH.
247 TargetOptions TargetOpts;
248 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000249 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000250 TargetOpts.CPU = "";
251 TargetOpts.Features.clear();
252 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000253 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
254 TargetOpts));
255 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
256 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000257 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000258 Preprocessor &PP = *AST->PP.get();
259
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000260 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000261 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000262 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000263
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000264 // Create and initialize the ASTContext.
265
266 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000267 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000268 *AST->Target.get(),
269 PP.getIdentifierTable(),
270 PP.getSelectorTable(),
271 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000272 /* size_reserve = */0));
273 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000274
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000275 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000277 // Attach the PCH reader to the AST context as an external AST
278 // source, so that declarations will be deserialized from the
279 // PCH file as needed.
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000280 Source.reset(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000281 Context.setExternalSource(Source);
282
Mike Stump11289f42009-09-09 15:08:12 +0000283 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000284}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000285
286namespace {
287
Daniel Dunbar644dca02009-12-04 08:17:33 +0000288class TopLevelDeclTrackerConsumer : public ASTConsumer {
289 ASTUnit &Unit;
290
291public:
292 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
293
294 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000295 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
296 Decl *D = *it;
297 // FIXME: Currently ObjC method declarations are incorrectly being
298 // reported as top-level declarations, even though their DeclContext
299 // is the containing ObjC @interface/@implementation. This is a
300 // fundamental problem in the parser right now.
301 if (isa<ObjCMethodDecl>(D))
302 continue;
303 Unit.getTopLevelDecls().push_back(D);
304 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000305 }
306};
307
308class TopLevelDeclTrackerAction : public ASTFrontendAction {
309public:
310 ASTUnit &Unit;
311
Daniel Dunbar764c0822009-12-01 09:51:01 +0000312 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
313 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000314 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000315 }
316
317public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000318 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
319
Daniel Dunbar764c0822009-12-01 09:51:01 +0000320 virtual bool hasCodeCompletionSupport() const { return false; }
321};
322
323}
324
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000325/// Parse the source file into a translation unit using the given compiler
326/// invocation, replacing the current translation unit.
327///
328/// \returns True if a failure occurred that causes the ASTUnit not to
329/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000330bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000331 if (!Invocation.get())
332 return true;
333
Daniel Dunbar764c0822009-12-01 09:51:01 +0000334 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000335 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000336 Clang.setInvocation(Invocation.take());
337 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
338
339 // Set up diagnostics.
340 Clang.setDiagnostics(&getDiagnostics());
341 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregord03e8232010-04-05 21:10:19 +0000342
Daniel Dunbar764c0822009-12-01 09:51:01 +0000343 // Create the target instance.
344 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
345 Clang.getTargetOpts()));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000346 if (!Clang.hasTarget()) {
Douglas Gregor33cdd812010-02-18 18:08:43 +0000347 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000348 return true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000349 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000350
Daniel Dunbar764c0822009-12-01 09:51:01 +0000351 // Inform the target of the language options.
352 //
353 // FIXME: We shouldn't need to do this, the target should be immutable once
354 // created. This complexity should be lifted elsewhere.
355 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000356
Daniel Dunbar764c0822009-12-01 09:51:01 +0000357 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
358 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000359 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000360 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000361 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
362 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000363
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000364 // Configure the various subsystems.
365 // FIXME: Should we retain the previous file manager?
366 FileMgr.reset(new FileManager);
367 SourceMgr.reset(new SourceManager(getDiagnostics()));
368 Ctx.reset();
369 PP.reset();
370
371 // Clear out old caches and data.
372 TopLevelDecls.clear();
373 StoredDiagnostics.clear();
374 CleanTemporaryFiles();
375 PreprocessedEntitiesByFile.clear();
376
Douglas Gregor33cdd812010-02-18 18:08:43 +0000377 // Capture any diagnostics that would otherwise be dropped.
378 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
379 Clang.getDiagnostics(),
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000380 StoredDiagnostics);
381
Daniel Dunbar764c0822009-12-01 09:51:01 +0000382 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000383 Clang.setFileManager(&getFileManager());
384
Daniel Dunbar764c0822009-12-01 09:51:01 +0000385 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000386 Clang.setSourceManager(&getSourceManager());
387
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000388 // If the main file has been overridden due to the use of a preamble,
389 // make that override happen and introduce the preamble.
390 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
391 if (OverrideMainBuffer) {
392 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
393 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
394 PreprocessorOpts.PrecompiledPreambleBytes.second
395 = PreambleEndsAtStartOfLine;
396 PreprocessorOpts.ImplicitPCHInclude = PreambleFile.str();
Douglas Gregorce3a8292010-07-27 00:27:13 +0000397 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000398 }
399
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000400 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
401 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000402 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000403 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000404 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000405
Daniel Dunbar644dca02009-12-04 08:17:33 +0000406 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000407
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000408 // Steal the created target, context, and preprocessor, and take back the
409 // source and file managers.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000410 Ctx.reset(Clang.takeASTContext());
411 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000412 Clang.takeSourceManager();
413 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000414 Target.reset(Clang.takeTarget());
415
Daniel Dunbar644dca02009-12-04 08:17:33 +0000416 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000417
418 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000419 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000420 PreprocessorOpts.eraseRemappedFile(
421 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000422 PreprocessorOpts.DisablePCHValidation = true;
423 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000424
Daniel Dunbar764c0822009-12-01 09:51:01 +0000425 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000426
427 Invocation.reset(Clang.takeInvocation());
428 return false;
429
Daniel Dunbar764c0822009-12-01 09:51:01 +0000430error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000431 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000432 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000433 PreprocessorOpts.eraseRemappedFile(
434 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000435 PreprocessorOpts.DisablePCHValidation = true;
436 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000437
Daniel Dunbar764c0822009-12-01 09:51:01 +0000438 Clang.takeSourceManager();
439 Clang.takeFileManager();
440 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000441 Invocation.reset(Clang.takeInvocation());
442 return true;
443}
444
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000445/// \brief Simple function to retrieve a path for a preamble precompiled header.
446static std::string GetPreamblePCHPath() {
447 // FIXME: This is lame; sys::Path should provide this function (in particular,
448 // it should know how to find the temporary files dir).
449 // FIXME: This is really lame. I copied this code from the Driver!
450 std::string Error;
451 const char *TmpDir = ::getenv("TMPDIR");
452 if (!TmpDir)
453 TmpDir = ::getenv("TEMP");
454 if (!TmpDir)
455 TmpDir = ::getenv("TMP");
456 if (!TmpDir)
457 TmpDir = "/tmp";
458 llvm::sys::Path P(TmpDir);
459 P.appendComponent("preamble");
460 if (P.createTemporaryFileOnDisk())
461 return std::string();
462
463 P.appendSuffix("pch");
464 return P.str();
465}
466
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000467/// \brief Compute the preamble for the main file, providing the source buffer
468/// that corresponds to the main file along with a pair (bytes, start-of-line)
469/// that describes the preamble.
470std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor4dde7492010-07-23 23:58:40 +0000471ASTUnit::ComputePreamble(CompilerInvocation &Invocation, bool &CreatedBuffer) {
472 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000473 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000474 = Invocation.getPreprocessorOpts();
475 CreatedBuffer = false;
476
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000477 // Try to determine if the main file has been remapped, either from the
478 // command line (to another file) or directly through the compiler invocation
479 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000480 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000481 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
482 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
483 // Check whether there is a file-file remapping of the main file
484 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000485 M = PreprocessorOpts.remapped_file_begin(),
486 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000487 M != E;
488 ++M) {
489 llvm::sys::PathWithStatus MPath(M->first);
490 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
491 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
492 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000493 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000494 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000495 CreatedBuffer = false;
496 }
497
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000498 Buffer = llvm::MemoryBuffer::getFile(M->second);
499 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000500 return std::make_pair((llvm::MemoryBuffer*)0,
501 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000502 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000503
Douglas Gregor4dde7492010-07-23 23:58:40 +0000504 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000505 M = PreprocessorOpts.eraseRemappedFile(M);
506 E = PreprocessorOpts.remapped_file_end();
507 }
508 }
509 }
510
511 // Check whether there is a file-buffer remapping. It supercedes the
512 // file-file remapping.
513 for (PreprocessorOptions::remapped_file_buffer_iterator
514 M = PreprocessorOpts.remapped_file_buffer_begin(),
515 E = PreprocessorOpts.remapped_file_buffer_end();
516 M != E;
517 ++M) {
518 llvm::sys::PathWithStatus MPath(M->first);
519 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
520 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
521 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000522 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000523 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000524 CreatedBuffer = false;
525 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000526
Douglas Gregor4dde7492010-07-23 23:58:40 +0000527 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
528
529 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000530 M = PreprocessorOpts.eraseRemappedFile(M);
531 E = PreprocessorOpts.remapped_file_buffer_end();
532 }
533 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000534 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000535 }
536
537 // If the main source file was not remapped, load it now.
538 if (!Buffer) {
539 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
540 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000541 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000542
543 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000544 }
545
Douglas Gregor4dde7492010-07-23 23:58:40 +0000546 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer));
547}
548
Douglas Gregor6481ef12010-07-24 00:38:13 +0000549static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
550 bool DeleteOld,
551 unsigned NewSize,
552 llvm::StringRef NewName) {
553 llvm::MemoryBuffer *Result
554 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
555 memcpy(const_cast<char*>(Result->getBufferStart()),
556 Old->getBufferStart(), Old->getBufferSize());
557 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000558 ' ', NewSize - Old->getBufferSize() - 1);
559 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000560
561 if (DeleteOld)
562 delete Old;
563
564 return Result;
565}
566
Douglas Gregor4dde7492010-07-23 23:58:40 +0000567/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
568/// the source file.
569///
570/// This routine will compute the preamble of the main source file. If a
571/// non-trivial preamble is found, it will precompile that preamble into a
572/// precompiled header so that the precompiled preamble can be used to reduce
573/// reparsing time. If a precompiled preamble has already been constructed,
574/// this routine will determine if it is still valid and, if so, avoid
575/// rebuilding the precompiled preamble.
576///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000577/// \returns If the precompiled preamble can be used, returns a newly-allocated
578/// buffer that should be used in place of the main file when doing so.
579/// Otherwise, returns a NULL pointer.
580llvm::MemoryBuffer *ASTUnit::BuildPrecompiledPreamble() {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000581 CompilerInvocation PreambleInvocation(*Invocation);
582 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
583 PreprocessorOptions &PreprocessorOpts
584 = PreambleInvocation.getPreprocessorOpts();
585
586 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000587 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor4dde7492010-07-23 23:58:40 +0000588 = ComputePreamble(PreambleInvocation, CreatedPreambleBuffer);
589
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000590 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000591 // We couldn't find a preamble in the main source. Clear out the current
592 // preamble, if we have one. It's obviously no good any more.
593 Preamble.clear();
594 if (!PreambleFile.empty()) {
595 PreambleFile.eraseFromDisk();
596 PreambleFile.clear();
597 }
598 if (CreatedPreambleBuffer)
599 delete NewPreamble.first;
600
Douglas Gregor6481ef12010-07-24 00:38:13 +0000601 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000602 }
603
604 if (!Preamble.empty()) {
605 // We've previously computed a preamble. Check whether we have the same
606 // preamble now that we did before, and that there's enough space in
607 // the main-file buffer within the precompiled preamble to fit the
608 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000609 if (Preamble.size() == NewPreamble.second.first &&
610 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000611 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000612 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000613 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000614 // The preamble has not changed. We may be able to re-use the precompiled
615 // preamble.
616 // FIXME: Check that none of the files used by the preamble have changed.
617
Douglas Gregor6481ef12010-07-24 00:38:13 +0000618
Douglas Gregor4dde7492010-07-23 23:58:40 +0000619 // Okay! Re-use the precompiled preamble.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000620 return CreatePaddedMainFileBuffer(NewPreamble.first,
621 CreatedPreambleBuffer,
622 PreambleReservedSize,
623 FrontendOpts.Inputs[0].second);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000624 }
625
626 // We can't reuse the previously-computed preamble. Build a new one.
627 Preamble.clear();
628 PreambleFile.eraseFromDisk();
629 }
630
631 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000632
633 // Create a new buffer that stores the preamble. The buffer also contains
634 // extra space for the original contents of the file (which will be present
635 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +0000636 // grows.
637 PreambleReservedSize = NewPreamble.first->getBufferSize();
638 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000639 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000640 else
Douglas Gregor4dde7492010-07-23 23:58:40 +0000641 PreambleReservedSize *= 2;
642
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000643 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +0000644 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000645 FrontendOpts.Inputs[0].second);
646 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +0000647 NewPreamble.first->getBufferStart(), Preamble.size());
648 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000649 ' ', PreambleReservedSize - Preamble.size() - 1);
650 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorf5275a82010-07-24 00:42:07 +0000651
Douglas Gregor4dde7492010-07-23 23:58:40 +0000652 // Save the preamble text for later; we'll need to compare against it for
653 // subsequent reparses.
654 Preamble.assign(NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000655 NewPreamble.first->getBufferStart()
656 + NewPreamble.second.first);
657 PreambleEndsAtStartOfLine = NewPreamble.second.second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000658
659 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000660 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000661 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
662
663 // Tell the compiler invocation to generate a temporary precompiled header.
664 FrontendOpts.ProgramAction = frontend::GeneratePCH;
665 // FIXME: Set ChainedPCH, once it is ready.
666 // FIXME: Generate the precompiled header into memory?
Douglas Gregor4dde7492010-07-23 23:58:40 +0000667 if (PreambleFile.isEmpty())
668 FrontendOpts.OutputFile = GetPreamblePCHPath();
669 else
670 FrontendOpts.OutputFile = PreambleFile.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000671
672 // Create the compiler instance to use for building the precompiled preamble.
673 CompilerInstance Clang;
674 Clang.setInvocation(&PreambleInvocation);
675 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
676
677 // Set up diagnostics.
678 Clang.setDiagnostics(&getDiagnostics());
679 Clang.setDiagnosticClient(getDiagnostics().getClient());
680
681 // Create the target instance.
682 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
683 Clang.getTargetOpts()));
684 if (!Clang.hasTarget()) {
685 Clang.takeDiagnosticClient();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000686 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
687 Preamble.clear();
688 if (CreatedPreambleBuffer)
689 delete NewPreamble.first;
690
Douglas Gregor6481ef12010-07-24 00:38:13 +0000691 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000692 }
693
694 // Inform the target of the language options.
695 //
696 // FIXME: We shouldn't need to do this, the target should be immutable once
697 // created. This complexity should be lifted elsewhere.
698 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
699
700 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
701 "Invocation must have exactly one source file!");
702 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
703 "FIXME: AST inputs not yet supported here!");
704 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
705 "IR inputs not support here!");
706
707 // Clear out old caches and data.
708 StoredDiagnostics.clear();
709
710 // Capture any diagnostics that would otherwise be dropped.
711 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
712 Clang.getDiagnostics(),
713 StoredDiagnostics);
714
715 // Create a file manager object to provide access to and cache the filesystem.
716 Clang.setFileManager(new FileManager);
717
718 // Create the source manager.
719 Clang.setSourceManager(new SourceManager(getDiagnostics()));
720
721 // FIXME: Eventually, we'll have to track top-level declarations here, too.
722 llvm::OwningPtr<GeneratePCHAction> Act;
723 Act.reset(new GeneratePCHAction);
724 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
725 Clang.getFrontendOpts().Inputs[0].first)) {
726 Clang.takeDiagnosticClient();
727 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000728 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
729 Preamble.clear();
730 if (CreatedPreambleBuffer)
731 delete NewPreamble.first;
732
Douglas Gregor6481ef12010-07-24 00:38:13 +0000733 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000734 }
735
736 Act->Execute();
737 Act->EndSourceFile();
738 Clang.takeDiagnosticClient();
739 Clang.takeInvocation();
740
Douglas Gregor4dde7492010-07-23 23:58:40 +0000741 if (Diagnostics->getNumErrors() > 0) {
742 // There were errors parsing the preamble, so no precompiled header was
743 // generated. Forget that we even tried.
744 // FIXME: Should we leave a note for ourselves to try again?
745 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
746 Preamble.clear();
747 if (CreatedPreambleBuffer)
748 delete NewPreamble.first;
749
Douglas Gregor6481ef12010-07-24 00:38:13 +0000750 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000751 }
752
753 // Keep track of the preamble we precompiled.
754 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000755 fprintf(stderr, "Preamble PCH: %s\n", FrontendOpts.OutputFile.c_str());
Douglas Gregor6481ef12010-07-24 00:38:13 +0000756 return CreatePaddedMainFileBuffer(NewPreamble.first,
757 CreatedPreambleBuffer,
758 PreambleReservedSize,
759 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000760}
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000761
762ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
763 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
764 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000765 bool CaptureDiagnostics,
766 bool PrecompilePreamble) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000767 if (!Diags.getPtr()) {
768 // No diagnostics engine was provided, so create our own diagnostics object
769 // with the default options.
770 DiagnosticOptions DiagOpts;
771 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
772 }
773
774 // Create the AST unit.
775 llvm::OwningPtr<ASTUnit> AST;
776 AST.reset(new ASTUnit(false));
777 AST->Diagnostics = Diags;
778 AST->CaptureDiagnostics = CaptureDiagnostics;
779 AST->OnlyLocalDecls = OnlyLocalDecls;
780 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000781 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000782
Douglas Gregor6481ef12010-07-24 00:38:13 +0000783 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000784 if (PrecompilePreamble)
Douglas Gregor6481ef12010-07-24 00:38:13 +0000785 OverrideMainBuffer = AST->BuildPrecompiledPreamble();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000786
Douglas Gregor6481ef12010-07-24 00:38:13 +0000787 if (!AST->Parse(OverrideMainBuffer))
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000788 return AST.take();
789
Douglas Gregor6481ef12010-07-24 00:38:13 +0000790 delete OverrideMainBuffer;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000791 return 0;
792}
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000793
794ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
795 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000796 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +0000797 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000798 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000799 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000800 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000801 bool CaptureDiagnostics,
802 bool PrecompilePreamble) {
Douglas Gregor7f95d262010-04-05 23:52:57 +0000803 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000804 // No diagnostics engine was provided, so create our own diagnostics object
805 // with the default options.
806 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000807 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000808 }
809
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000810 llvm::SmallVector<const char *, 16> Args;
811 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
812 Args.insert(Args.end(), ArgBegin, ArgEnd);
813
814 // FIXME: Find a cleaner way to force the driver into restricted modes. We
815 // also want to force it to use clang.
816 Args.push_back("-fsyntax-only");
817
Daniel Dunbar8d4a2022009-12-13 03:46:13 +0000818 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +0000819 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000820 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +0000821
822 // Don't check that inputs exist, they have been remapped.
823 TheDriver.setCheckInputsExist(false);
824
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000825 llvm::OwningPtr<driver::Compilation> C(
826 TheDriver.BuildCompilation(Args.size(), Args.data()));
827
828 // We expect to get back exactly one command job, if we didn't something
829 // failed.
830 const driver::JobList &Jobs = C->getJobs();
831 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
832 llvm::SmallString<256> Msg;
833 llvm::raw_svector_ostream OS(Msg);
834 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +0000835 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000836 return 0;
837 }
838
839 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
840 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +0000841 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000842 return 0;
843 }
844
845 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000846 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +0000847 CompilerInvocation::CreateFromArgs(*CI,
848 const_cast<const char **>(CCArgs.data()),
849 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000850 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000851 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +0000852
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000853 // Override any files that need remapping
854 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000855 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +0000856 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000857
Daniel Dunbara5a166d2009-12-15 00:06:45 +0000858 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000859 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000860
Daniel Dunbar19511922010-02-16 01:55:04 +0000861 CI->getFrontendOpts().DisableFree = true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000862 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000863 CaptureDiagnostics, PrecompilePreamble);
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000864}
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000865
866bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
867 if (!Invocation.get())
868 return true;
869
Douglas Gregor4dde7492010-07-23 23:58:40 +0000870 // If we have a preamble file lying around, build or reuse the precompiled
871 // preamble.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000872 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000873 if (!PreambleFile.empty())
Douglas Gregor6481ef12010-07-24 00:38:13 +0000874 OverrideMainBuffer = BuildPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000875
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000876 // Clear out the diagnostics state.
877 getDiagnostics().Reset();
878
879 // Remap files.
880 Invocation->getPreprocessorOpts().clearRemappedFiles();
881 for (unsigned I = 0; I != NumRemappedFiles; ++I)
882 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Douglas Gregor4dde7492010-07-23 23:58:40 +0000883 RemappedFiles[I].second);
884
885 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +0000886 bool Result = Parse(OverrideMainBuffer);
887 delete OverrideMainBuffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000888 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000889}