blob: e37afae5332a0f92edd761867ed546a846e9a621 [file] [log] [blame]
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00001//===--- FrontendActions.cpp ----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/FrontendActions.h"
10#include "clang/AST/ASTConsumer.h"
11#include "clang/Basic/FileManager.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000012#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000013#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000015#include "clang/Frontend/MultiplexConsumer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000016#include "clang/Frontend/Utils.h"
Alex Lorenz6e2d36b2019-06-03 22:59:17 +000017#include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000020#include "clang/Lex/PreprocessorOptions.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000021#include "clang/Sema/TemplateInstCallback.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000022#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000023#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000024#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000025#include "llvm/Support/MemoryBuffer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000026#include "llvm/Support/Path.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000027#include "llvm/Support/YAMLTraits.h"
Alex Lorenz6e2d36b2019-06-03 22:59:17 +000028#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000029#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000030#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000031
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000032using namespace clang;
33
Gabor Horvath207e7b12018-02-10 14:04:45 +000034namespace {
35CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
36 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
37 : nullptr;
38}
39
40void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
41 if (Action.hasCodeCompletionSupport() &&
42 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
43 CI.createCodeCompletionConsumer();
44
45 if (!CI.hasSema())
46 CI.createSema(Action.getTranslationUnitKind(),
47 GetCodeCompletionConsumer(CI));
48}
49} // namespace
50
Daniel Dunbar88357802009-11-14 10:42:57 +000051//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000052// Custom Actions
53//===----------------------------------------------------------------------===//
54
David Blaikie6beb6aa2014-08-10 19:56:51 +000055std::unique_ptr<ASTConsumer>
56InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
57 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000058}
59
60void InitOnlyAction::ExecuteAction() {
61}
62
63//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000064// AST Consumer Actions
65//===----------------------------------------------------------------------===//
66
David Blaikie6beb6aa2014-08-10 19:56:51 +000067std::unique_ptr<ASTConsumer>
68ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Peter Collingbourne03f89072016-07-15 00:55:40 +000069 if (std::unique_ptr<raw_ostream> OS =
70 CI.createDefaultOutputFile(false, InFile))
71 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000072 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000073}
74
David Blaikie6beb6aa2014-08-10 19:56:51 +000075std::unique_ptr<ASTConsumer>
76ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Aaron Ballman2ce598a2019-05-13 21:39:55 +000077 const FrontendOptions &Opts = CI.getFrontendOpts();
78 return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
79 Opts.ASTDumpDecls, Opts.ASTDumpAll,
80 Opts.ASTDumpLookups, Opts.ASTDumpFormat);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000081}
82
David Blaikie6beb6aa2014-08-10 19:56:51 +000083std::unique_ptr<ASTConsumer>
84ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000085 return CreateASTDeclNodeLister();
86}
87
David Blaikie6beb6aa2014-08-10 19:56:51 +000088std::unique_ptr<ASTConsumer>
89ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000090 return CreateASTViewer();
91}
92
David Blaikie6beb6aa2014-08-10 19:56:51 +000093std::unique_ptr<ASTConsumer>
David Blaikie6beb6aa2014-08-10 19:56:51 +000094GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000095 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +000096 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
97 return nullptr;
98
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000099 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000100 std::unique_ptr<raw_pwrite_stream> OS =
Ilya Biryukov417085a2017-11-16 16:25:01 +0000101 CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000102 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000103 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000104
Douglas Gregorc567ba22011-07-22 16:35:34 +0000105 if (!CI.getFrontendOpts().RelocatablePCH)
106 Sysroot.clear();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000107
Hans Wennborg08c5a7b2018-06-25 13:23:49 +0000108 const auto &FrontendOpts = CI.getFrontendOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000109 auto Buffer = std::make_shared<PCHBuffer>();
110 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
111 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000112 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
113 FrontendOpts.ModuleFileExtensions,
114 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +0000115 FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
Adrian Prantl03914062015-09-18 22:10:59 +0000116 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000117 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000118
119 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000120}
121
Ilya Biryukov417085a2017-11-16 16:25:01 +0000122bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
123 std::string &Sysroot) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000124 Sysroot = CI.getHeaderSearchOpts().Sysroot;
125 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000126 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000127 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000128 }
129
Ilya Biryukov417085a2017-11-16 16:25:01 +0000130 return true;
131}
132
133std::unique_ptr<llvm::raw_pwrite_stream>
134GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
135 std::string &OutputFile) {
Daniel Dunbara2867c72011-01-31 22:00:44 +0000136 // We use createOutputFile here because this is exposed via libclang, and we
137 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000138 // We use a temporary to avoid race conditions.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000139 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000140 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
141 /*RemoveFileOnSignal=*/false, InFile,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000142 /*Extension=*/"", /*UseTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000143 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000144 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000145
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000146 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000147 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000148}
149
Argyrios Kyrtzidiscf486b22017-02-27 03:52:36 +0000150bool GeneratePCHAction::shouldEraseOutputFiles() {
151 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
152 return false;
153 return ASTFrontendAction::shouldEraseOutputFiles();
154}
155
Richard Smithd9259c22017-06-09 01:36:10 +0000156bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
Manman Renffd3e9d2017-01-09 19:20:18 +0000157 CI.getLangOpts().CompilingPCH = true;
158 return true;
159}
160
David Blaikie6beb6aa2014-08-10 19:56:51 +0000161std::unique_ptr<ASTConsumer>
162GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
163 StringRef InFile) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000164 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000165 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000166 return nullptr;
167
Richard Smithbbcc9f02016-08-26 00:14:38 +0000168 std::string OutputFile = CI.getFrontendOpts().OutputFile;
169 std::string Sysroot;
170
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000171 auto Buffer = std::make_shared<PCHBuffer>();
172 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000173
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000174 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000175 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
176 CI.getFrontendOpts().ModuleFileExtensions,
177 /*AllowASTWithErrors=*/false,
178 /*IncludeTimestamps=*/
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +0000179 +CI.getFrontendOpts().BuildingImplicitModule,
180 /*ShouldCacheASTInMemory=*/
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000181 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000182 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000183 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000184 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000185}
186
Richard Smith1f2bd352017-07-06 21:05:56 +0000187bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
188 CompilerInstance &CI) {
189 if (!CI.getLangOpts().Modules) {
190 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
191 return false;
192 }
193
194 return GenerateModuleAction::BeginSourceFileAction(CI);
195}
196
Peter Collingbourne03f89072016-07-15 00:55:40 +0000197std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000198GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
199 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000200 // If no output file was provided, figure out where this module would go
201 // in the module cache.
202 if (CI.getFrontendOpts().OutputFile.empty()) {
Richard Smithf74d9462017-04-28 01:49:42 +0000203 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
204 if (ModuleMapFile.empty())
205 ModuleMapFile = InFile;
206
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000207 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000208 CI.getFrontendOpts().OutputFile =
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000209 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
210 ModuleMapFile);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000211 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000212
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000213 // We use createOutputFile here because this is exposed via libclang, and we
214 // must disable the RemoveFileOnSignal behavior.
215 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000216 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
217 /*RemoveFileOnSignal=*/false, InFile,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000218 /*Extension=*/"", /*UseTemporary=*/true,
Richard Smithbbcc9f02016-08-26 00:14:38 +0000219 /*CreateMissingDirectories=*/true);
220}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000221
Richard Smithd9259c22017-06-09 01:36:10 +0000222bool GenerateModuleInterfaceAction::BeginSourceFileAction(
223 CompilerInstance &CI) {
Richard Smithb1b580e2019-04-14 11:11:37 +0000224 if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
225 CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000226 return false;
227 }
228
229 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
230
Richard Smithd9259c22017-06-09 01:36:10 +0000231 return GenerateModuleAction::BeginSourceFileAction(CI);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000232}
233
234std::unique_ptr<raw_pwrite_stream>
235GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
236 StringRef InFile) {
237 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000238}
239
Richard Smithd6509cf2018-09-15 01:21:15 +0000240bool GenerateHeaderModuleAction::PrepareToExecuteAction(
241 CompilerInstance &CI) {
Richard Smithb1b580e2019-04-14 11:11:37 +0000242 if (!CI.getLangOpts().Modules) {
Richard Smithd6509cf2018-09-15 01:21:15 +0000243 CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
244 return false;
245 }
246
247 auto &Inputs = CI.getFrontendOpts().Inputs;
248 if (Inputs.empty())
249 return GenerateModuleAction::BeginInvocation(CI);
250
251 auto Kind = Inputs[0].getKind();
252
253 // Convert the header file inputs into a single module input buffer.
254 SmallString<256> HeaderContents;
255 ModuleHeaders.reserve(Inputs.size());
256 for (const FrontendInputFile &FIF : Inputs) {
257 // FIXME: We should support re-compiling from an AST file.
258 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
259 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
260 << (FIF.isFile() ? FIF.getFile()
261 : FIF.getBuffer()->getBufferIdentifier());
262 return true;
263 }
264
265 HeaderContents += "#include \"";
266 HeaderContents += FIF.getFile();
267 HeaderContents += "\"\n";
268 ModuleHeaders.push_back(FIF.getFile());
269 }
270 Buffer = llvm::MemoryBuffer::getMemBufferCopy(
271 HeaderContents, Module::getModuleInputBufferName());
272
273 // Set that buffer up as our "real" input.
274 Inputs.clear();
275 Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false));
276
277 return GenerateModuleAction::PrepareToExecuteAction(CI);
278}
279
280bool GenerateHeaderModuleAction::BeginSourceFileAction(
281 CompilerInstance &CI) {
282 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
283
284 // Synthesize a Module object for the given headers.
285 auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
286 SmallVector<Module::Header, 16> Headers;
287 for (StringRef Name : ModuleHeaders) {
288 const DirectoryLookup *CurDir = nullptr;
289 const FileEntry *FE = HS.LookupFile(
290 Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000291 None, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
Richard Smithd6509cf2018-09-15 01:21:15 +0000292 if (!FE) {
293 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
294 << Name;
295 continue;
296 }
297 Headers.push_back({Name, FE});
298 }
299 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
300
301 return GenerateModuleAction::BeginSourceFileAction(CI);
302}
303
304std::unique_ptr<raw_pwrite_stream>
305GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
306 StringRef InFile) {
307 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
308}
309
Etienne Bergeron98de8052016-05-12 19:51:18 +0000310SyntaxOnlyAction::~SyntaxOnlyAction() {
311}
312
David Blaikie6beb6aa2014-08-10 19:56:51 +0000313std::unique_ptr<ASTConsumer>
314SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
315 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000316}
317
David Blaikie6beb6aa2014-08-10 19:56:51 +0000318std::unique_ptr<ASTConsumer>
319DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
320 StringRef InFile) {
321 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000322}
323
David Blaikie6beb6aa2014-08-10 19:56:51 +0000324std::unique_ptr<ASTConsumer>
325VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
326 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000327}
328
329void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000330 CompilerInstance &CI = getCompilerInstance();
331 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
332 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000333 std::unique_ptr<ASTReader> Reader(new ASTReader(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000334 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
335 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000336 Sysroot.empty() ? "" : Sysroot.c_str(),
337 /*DisableValidation*/ false,
338 /*AllowPCHWithCompilerErrors*/ false,
339 /*AllowConfigurationMismatch*/ true,
340 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000341
342 Reader->ReadAST(getCurrentFile(),
343 Preamble ? serialization::MK_Preamble
344 : serialization::MK_PCH,
345 SourceLocation(),
346 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000347}
348
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000349namespace {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000350struct TemplightEntry {
351 std::string Name;
352 std::string Kind;
353 std::string Event;
354 std::string DefinitionLocation;
355 std::string PointOfInstantiation;
356};
357} // namespace
358
359namespace llvm {
360namespace yaml {
361template <> struct MappingTraits<TemplightEntry> {
362 static void mapping(IO &io, TemplightEntry &fields) {
363 io.mapRequired("name", fields.Name);
364 io.mapRequired("kind", fields.Kind);
365 io.mapRequired("event", fields.Event);
366 io.mapRequired("orig", fields.DefinitionLocation);
367 io.mapRequired("poi", fields.PointOfInstantiation);
368 }
369};
370} // namespace yaml
371} // namespace llvm
372
373namespace {
374class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
375 using CodeSynthesisContext = Sema::CodeSynthesisContext;
376
377public:
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000378 void initialize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000379
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000380 void finalize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000381
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000382 void atTemplateBegin(const Sema &TheSema,
383 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000384 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
385 }
386
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000387 void atTemplateEnd(const Sema &TheSema,
388 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000389 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
390 }
391
392private:
393 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
394 switch (Kind) {
395 case CodeSynthesisContext::TemplateInstantiation:
396 return "TemplateInstantiation";
397 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
398 return "DefaultTemplateArgumentInstantiation";
399 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
400 return "DefaultFunctionArgumentInstantiation";
401 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
402 return "ExplicitTemplateArgumentSubstitution";
403 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
404 return "DeducedTemplateArgumentSubstitution";
405 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
406 return "PriorTemplateArgumentSubstitution";
407 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
408 return "DefaultTemplateArgumentChecking";
Richard Smith5159bbad2018-09-05 22:30:37 +0000409 case CodeSynthesisContext::ExceptionSpecEvaluation:
410 return "ExceptionSpecEvaluation";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000411 case CodeSynthesisContext::ExceptionSpecInstantiation:
412 return "ExceptionSpecInstantiation";
413 case CodeSynthesisContext::DeclaringSpecialMember:
414 return "DeclaringSpecialMember";
415 case CodeSynthesisContext::DefiningSynthesizedFunction:
416 return "DefiningSynthesizedFunction";
417 case CodeSynthesisContext::Memoization:
418 return "Memoization";
419 }
420 return "";
421 }
422
423 template <bool BeginInstantiation>
424 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
425 const CodeSynthesisContext &Inst) {
426 std::string YAML;
427 {
428 llvm::raw_string_ostream OS(YAML);
429 llvm::yaml::Output YO(OS);
430 TemplightEntry Entry =
431 getTemplightEntry<BeginInstantiation>(TheSema, Inst);
432 llvm::yaml::EmptyContext Context;
433 llvm::yaml::yamlize(YO, Entry, true, Context);
434 }
435 Out << "---" << YAML << "\n";
436 }
437
438 template <bool BeginInstantiation>
439 static TemplightEntry getTemplightEntry(const Sema &TheSema,
440 const CodeSynthesisContext &Inst) {
441 TemplightEntry Entry;
442 Entry.Kind = toString(Inst.Kind);
443 Entry.Event = BeginInstantiation ? "Begin" : "End";
444 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
445 llvm::raw_string_ostream OS(Entry.Name);
446 NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +0000447 const PresumedLoc DefLoc =
Gabor Horvath207e7b12018-02-10 14:04:45 +0000448 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
449 if(!DefLoc.isInvalid())
450 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
451 std::to_string(DefLoc.getLine()) + ":" +
452 std::to_string(DefLoc.getColumn());
453 }
454 const PresumedLoc PoiLoc =
455 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
456 if (!PoiLoc.isInvalid()) {
457 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
458 std::to_string(PoiLoc.getLine()) + ":" +
459 std::to_string(PoiLoc.getColumn());
460 }
461 return Entry;
462 }
463};
464} // namespace
465
466std::unique_ptr<ASTConsumer>
467TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
468 return llvm::make_unique<ASTConsumer>();
469}
470
471void TemplightDumpAction::ExecuteAction() {
472 CompilerInstance &CI = getCompilerInstance();
473
474 // This part is normally done by ASTFrontEndAction, but needs to happen
475 // before Templight observers can be created
476 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
477 // here so the source manager would be initialized.
478 EnsureSemaIsCreated(CI, *this);
479
480 CI.getSema().TemplateInstCallbacks.push_back(
481 llvm::make_unique<DefaultTemplateInstCallback>());
482 ASTFrontendAction::ExecuteAction();
483}
484
485namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// AST reader listener that dumps module information for a module
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000487 /// file.
488 class DumpModuleInfoListener : public ASTReaderListener {
489 llvm::raw_ostream &Out;
490
491 public:
492 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
493
494#define DUMP_BOOLEAN(Value, Text) \
495 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
496
Craig Topperafa7cb32014-03-13 06:07:04 +0000497 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000498 Out.indent(2)
499 << "Generated by "
500 << (FullVersion == getClangFullRepositoryVersion()? "this"
501 : "a different")
502 << " Clang: " << FullVersion << "\n";
503 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
504 }
505
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000506 void ReadModuleName(StringRef ModuleName) override {
507 Out.indent(2) << "Module name: " << ModuleName << "\n";
508 }
509 void ReadModuleMapFile(StringRef ModuleMapPath) override {
510 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
511 }
512
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000513 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
514 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000515 Out.indent(2) << "Language options:\n";
516#define LANGOPT(Name, Bits, Default, Description) \
517 DUMP_BOOLEAN(LangOpts.Name, Description);
518#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
519 Out.indent(4) << Description << ": " \
520 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
521#define VALUE_LANGOPT(Name, Bits, Default, Description) \
522 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
523#define BENIGN_LANGOPT(Name, Bits, Default, Description)
524#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
525#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000526
527 if (!LangOpts.ModuleFeatures.empty()) {
528 Out.indent(4) << "Module features:\n";
529 for (StringRef Feature : LangOpts.ModuleFeatures)
530 Out.indent(6) << Feature << "\n";
531 }
532
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000533 return false;
534 }
535
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000536 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
537 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000538 Out.indent(2) << "Target options:\n";
539 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
540 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
541 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000542
543 if (!TargetOpts.FeaturesAsWritten.empty()) {
544 Out.indent(4) << "Target features:\n";
545 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
546 I != N; ++I) {
547 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
548 }
549 }
550
551 return false;
552 }
553
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000554 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
555 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000556 Out.indent(2) << "Diagnostic options:\n";
557#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
558#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
559 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
560#define VALUE_DIAGOPT(Name, Bits, Default) \
561 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
562#include "clang/Basic/DiagnosticOptions.def"
563
Richard Smith3be1cb22014-08-07 00:24:21 +0000564 Out.indent(4) << "Diagnostic flags:\n";
565 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000566 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000567 for (const std::string &Remark : DiagOpts->Remarks)
568 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000569
570 return false;
571 }
572
Craig Topperafa7cb32014-03-13 06:07:04 +0000573 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000574 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000575 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000576 Out.indent(2) << "Header search options:\n";
577 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbdff27d2017-02-25 18:14:31 +0000578 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000579 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000580 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
581 "Use builtin include directories [-nobuiltininc]");
582 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
583 "Use standard system include directories [-nostdinc]");
584 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
585 "Use standard C++ include directories [-nostdinc++]");
586 DUMP_BOOLEAN(HSOpts.UseLibcxx,
587 "Use libc++ (rather than libstdc++) [-stdlib=]");
588 return false;
589 }
590
Craig Topperafa7cb32014-03-13 06:07:04 +0000591 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
592 bool Complain,
593 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000594 Out.indent(2) << "Preprocessor options:\n";
595 DUMP_BOOLEAN(PPOpts.UsePredefines,
596 "Uses compiler/target-specific predefines [-undef]");
597 DUMP_BOOLEAN(PPOpts.DetailedRecord,
598 "Uses detailed preprocessing record (for indexing)");
599
600 if (!PPOpts.Macros.empty()) {
601 Out.indent(4) << "Predefined macros:\n";
602 }
603
604 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
605 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
606 I != IEnd; ++I) {
607 Out.indent(6);
608 if (I->second)
609 Out << "-U";
610 else
611 Out << "-D";
612 Out << I->first << "\n";
613 }
614 return false;
615 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000616
617 /// Indicates that a particular module file extension has been read.
618 void readModuleFileExtension(
619 const ModuleFileExtensionMetadata &Metadata) override {
620 Out.indent(2) << "Module file extension '"
621 << Metadata.BlockName << "' " << Metadata.MajorVersion
622 << "." << Metadata.MinorVersion;
623 if (!Metadata.UserInfo.empty()) {
624 Out << ": ";
625 Out.write_escaped(Metadata.UserInfo);
626 }
627
628 Out << "\n";
629 }
Vassil Vassilev33eb7292018-07-18 06:49:33 +0000630
631 /// Tells the \c ASTReaderListener that we want to receive the
632 /// input files of the AST file via \c visitInputFile.
633 bool needsInputFileVisitation() override { return true; }
634
635 /// Tells the \c ASTReaderListener that we want to receive the
636 /// input files of the AST file via \c visitInputFile.
637 bool needsSystemInputFileVisitation() override { return true; }
638
639 /// Indicates that the AST file contains particular input file.
640 ///
641 /// \returns true to continue receiving the next input file, false to stop.
642 bool visitInputFile(StringRef Filename, bool isSystem,
643 bool isOverridden, bool isExplicitModule) override {
644
645 Out.indent(2) << "Input file: " << Filename;
646
647 if (isSystem || isOverridden || isExplicitModule) {
648 Out << " [";
649 if (isSystem) {
650 Out << "System";
651 if (isOverridden || isExplicitModule)
652 Out << ", ";
653 }
654 if (isOverridden) {
655 Out << "Overridden";
656 if (isExplicitModule)
657 Out << ", ";
658 }
659 if (isExplicitModule)
660 Out << "ExplicitModule";
661
662 Out << "]";
663 }
664
665 Out << "\n";
666
667 return true;
668 }
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +0000669
670 /// Returns true if this \c ASTReaderListener wants to receive the
671 /// imports of the AST file via \c visitImport, false otherwise.
672 bool needsImportVisitation() const override { return true; }
673
674 /// If needsImportVisitation returns \c true, this is called for each
675 /// AST file imported by this AST file.
676 void visitImport(StringRef ModuleName, StringRef Filename) override {
677 Out.indent(2) << "Imports module '" << ModuleName
678 << "': " << Filename.str() << "\n";
679 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000680#undef DUMP_BOOLEAN
681 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000682}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000683
Adrian Prantl576b2db2016-08-17 23:13:53 +0000684bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
685 // The Object file reader also supports raw ast files and there is no point in
686 // being strict about the module file format in -module-file-info mode.
687 CI.getHeaderSearchOpts().ModuleFormat = "obj";
688 return true;
689}
690
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000691void DumpModuleInfoAction::ExecuteAction() {
692 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000693 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000694 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
695 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000696 std::error_code EC;
697 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
698 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000699 }
700 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
701
702 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000703 auto &FileMgr = getCompilerInstance().getFileManager();
704 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
705 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
706 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
707 Magic[2] == 'C' && Magic[3] == 'H');
708 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000709
Manman Ren47a44452016-07-26 17:12:17 +0000710 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000711 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000712 HeaderSearchOptions &HSOpts =
713 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000714 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000715 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000716 /*FindModuleFileExtensions=*/true, Listener,
717 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000718}
719
Daniel Dunbar88357802009-11-14 10:42:57 +0000720//===----------------------------------------------------------------------===//
721// Preprocessor Actions
722//===----------------------------------------------------------------------===//
723
724void DumpRawTokensAction::ExecuteAction() {
725 Preprocessor &PP = getCompilerInstance().getPreprocessor();
726 SourceManager &SM = PP.getSourceManager();
727
728 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000729 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000730 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000731 RawLex.SetKeepWhitespaceMode(true);
732
733 Token RawTok;
734 RawLex.LexFromRawLexer(RawTok);
735 while (RawTok.isNot(tok::eof)) {
736 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000737 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000738 RawLex.LexFromRawLexer(RawTok);
739 }
740}
741
742void DumpTokensAction::ExecuteAction() {
743 Preprocessor &PP = getCompilerInstance().getPreprocessor();
744 // Start preprocessing the specified input file.
745 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000746 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000747 do {
748 PP.Lex(Tok);
749 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000750 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000751 } while (Tok.isNot(tok::eof));
752}
753
Daniel Dunbar88357802009-11-14 10:42:57 +0000754void PreprocessOnlyAction::ExecuteAction() {
755 Preprocessor &PP = getCompilerInstance().getPreprocessor();
756
Daniel Dunbard839e772010-06-11 20:10:12 +0000757 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000758 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000759
Daniel Dunbar88357802009-11-14 10:42:57 +0000760 Token Tok;
761 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000762 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000763 do {
764 PP.Lex(Tok);
765 } while (Tok.isNot(tok::eof));
766}
767
Daniel Dunbar88357802009-11-14 10:42:57 +0000768void PrintPreprocessedAction::ExecuteAction() {
769 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000770 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000771 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000772 //
773 // Look to see what type of line endings the file uses. If there's a
774 // CRLF, then we won't open the file up in binary mode. If there is
775 // just an LF or CR, then we will open the file up in binary mode.
776 // In this fashion, the output format should match the input format, unless
777 // the input format has inconsistent line endings.
778 //
779 // This should be a relatively fast operation since most files won't have
Fangrui Song6907ce22018-07-30 19:24:48 +0000780 // all of their source code on a single line. However, that is still a
Douglas Gregor52da28b2011-09-23 23:43:36 +0000781 // concern, so if we scan for too long, we'll just assume the file should
782 // be opened in binary mode.
783 bool BinaryMode = true;
784 bool InvalidFile = false;
785 const SourceManager& SM = CI.getSourceManager();
Fangrui Song6907ce22018-07-30 19:24:48 +0000786 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
Douglas Gregor52da28b2011-09-23 23:43:36 +0000787 &InvalidFile);
788 if (!InvalidFile) {
789 const char *cur = Buffer->getBufferStart();
790 const char *end = Buffer->getBufferEnd();
791 const char *next = (cur != end) ? cur + 1 : end;
792
793 // Limit ourselves to only scanning 256 characters into the source
Fangrui Song6907ce22018-07-30 19:24:48 +0000794 // file. This is mostly a sanity check in case the file has no
Douglas Gregor52da28b2011-09-23 23:43:36 +0000795 // newlines whatsoever.
796 if (end - cur > 256) end = cur + 256;
Aaron Ballman4fc36ae2017-06-16 20:52:59 +0000797
Douglas Gregor52da28b2011-09-23 23:43:36 +0000798 while (next < end) {
799 if (*cur == 0x0D) { // CR
800 if (*next == 0x0A) // CRLF
801 BinaryMode = false;
802
803 break;
804 } else if (*cur == 0x0A) // LF
805 break;
806
Richard Trieucc3949d2016-02-18 22:34:54 +0000807 ++cur;
808 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000809 }
810 }
811
Peter Collingbourne03f89072016-07-15 00:55:40 +0000812 std::unique_ptr<raw_ostream> OS =
Richard Smith8b464f22018-09-15 01:21:18 +0000813 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
Daniel Dunbar75546992009-12-03 09:13:30 +0000814 if (!OS) return;
815
Richard Smith8128f332017-05-05 22:18:51 +0000816 // If we're preprocessing a module map, start by dumping the contents of the
817 // module itself before switching to the input buffer.
818 auto &Input = getCurrentInput();
819 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
Richard Smithc784e962017-06-01 20:10:35 +0000820 if (Input.isFile()) {
821 (*OS) << "# 1 \"";
822 OS->write_escaped(Input.getFile());
823 (*OS) << "\"\n";
824 }
Richard Smith8128f332017-05-05 22:18:51 +0000825 getCurrentModule()->print(*OS);
826 (*OS) << "#pragma clang module contents\n";
827 }
828
Peter Collingbourne03f89072016-07-15 00:55:40 +0000829 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000830 CI.getPreprocessorOutputOpts());
831}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000832
833void PrintPreambleAction::ExecuteAction() {
Richard Smith40c0efa2017-04-26 18:57:40 +0000834 switch (getCurrentFileKind().getLanguage()) {
835 case InputKind::C:
836 case InputKind::CXX:
837 case InputKind::ObjC:
838 case InputKind::ObjCXX:
839 case InputKind::OpenCL:
840 case InputKind::CUDA:
Yaxun Liu887c5692018-04-25 01:10:37 +0000841 case InputKind::HIP:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000842 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000843
Richard Smith40c0efa2017-04-26 18:57:40 +0000844 case InputKind::Unknown:
845 case InputKind::Asm:
846 case InputKind::LLVM_IR:
847 case InputKind::RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000848 // We can't do anything with these.
849 return;
850 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000851
Richard Smith40c0efa2017-04-26 18:57:40 +0000852 // We don't expect to find any #include directives in a preprocessed input.
853 if (getCurrentFileKind().isPreprocessed())
854 return;
855
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000856 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000857 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
858 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000859 unsigned Preamble =
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000860 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
Benjamin Kramera8857962014-10-26 22:44:13 +0000861 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000862 }
863}
Aaron Ballman16ed8dd2018-05-31 13:57:09 +0000864
865void DumpCompilerOptionsAction::ExecuteAction() {
866 CompilerInstance &CI = getCompilerInstance();
867 std::unique_ptr<raw_ostream> OSP =
868 CI.createDefaultOutputFile(false, getCurrentFile());
869 if (!OSP)
870 return;
871
872 raw_ostream &OS = *OSP;
873 const Preprocessor &PP = CI.getPreprocessor();
874 const LangOptions &LangOpts = PP.getLangOpts();
875
876 // FIXME: Rather than manually format the JSON (which is awkward due to
877 // needing to remove trailing commas), this should make use of a JSON library.
878 // FIXME: Instead of printing enums as an integral value and specifying the
879 // type as a separate field, use introspection to print the enumerator.
880
881 OS << "{\n";
882 OS << "\n\"features\" : [\n";
883 {
884 llvm::SmallString<128> Str;
885#define FEATURE(Name, Predicate) \
886 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
887 .toVector(Str);
888#include "clang/Basic/Features.def"
889#undef FEATURE
890 // Remove the newline and comma from the last entry to ensure this remains
891 // valid JSON.
892 OS << Str.substr(0, Str.size() - 2);
893 }
894 OS << "\n],\n";
895
896 OS << "\n\"extensions\" : [\n";
897 {
898 llvm::SmallString<128> Str;
899#define EXTENSION(Name, Predicate) \
900 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
901 .toVector(Str);
902#include "clang/Basic/Features.def"
903#undef EXTENSION
904 // Remove the newline and comma from the last entry to ensure this remains
905 // valid JSON.
906 OS << Str.substr(0, Str.size() - 2);
907 }
908 OS << "\n]\n";
909
910 OS << "}";
911}
Alex Lorenz6e2d36b2019-06-03 22:59:17 +0000912
913void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
914 CompilerInstance &CI = getCompilerInstance();
915 SourceManager &SM = CI.getPreprocessor().getSourceManager();
916 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
917
918 llvm::SmallString<1024> Output;
919 llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks;
920 if (minimizeSourceToDependencyDirectives(
921 FromFile->getBuffer(), Output, Toks, &CI.getDiagnostics(),
922 SM.getLocForStartOfFile(SM.getMainFileID()))) {
923 assert(CI.getDiagnostics().hasErrorOccurred() &&
924 "no errors reported for failure");
925
926 // Preprocess the source when verifying the diagnostics to capture the
927 // 'expected' comments.
928 if (CI.getDiagnosticOpts().VerifyDiagnostics) {
929 // Make sure we don't emit new diagnostics!
930 CI.getDiagnostics().setSuppressAllDiagnostics();
931 Preprocessor &PP = getCompilerInstance().getPreprocessor();
932 PP.EnterMainSourceFile();
933 Token Tok;
934 do {
935 PP.Lex(Tok);
936 } while (Tok.isNot(tok::eof));
937 }
938 return;
939 }
940 llvm::outs() << Output;
941}