blob: a407dfc162bb132a02913969b86f2edab05422ba [file] [log] [blame]
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00001//===--- FrontendActions.cpp ----------------------------------------------===//
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#include "clang/Frontend/FrontendActions.h"
11#include "clang/AST/ASTConsumer.h"
12#include "clang/Basic/FileManager.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000013#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000014#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000016#include "clang/Frontend/MultiplexConsumer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000017#include "clang/Frontend/Utils.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"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000027#include "llvm/Support/raw_ostream.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000028#include "llvm/Support/YAMLTraits.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) {
Alexander Kornienkod10d7902018-04-06 13:01:12 +000077 return CreateASTDumper(nullptr /*Dump to stdout.*/,
78 CI.getFrontendOpts().ASTDumpFilter,
Richard Smith35f986d2014-08-11 22:11:07 +000079 CI.getFrontendOpts().ASTDumpDecls,
Richard Smith3a36ac12017-03-09 22:00:01 +000080 CI.getFrontendOpts().ASTDumpAll,
Richard Smith6ea05822013-06-24 01:45:33 +000081 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000082}
83
David Blaikie6beb6aa2014-08-10 19:56:51 +000084std::unique_ptr<ASTConsumer>
85ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000086 return CreateASTDeclNodeLister();
87}
88
David Blaikie6beb6aa2014-08-10 19:56:51 +000089std::unique_ptr<ASTConsumer>
90ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000091 return CreateASTViewer();
92}
93
David Blaikie6beb6aa2014-08-10 19:56:51 +000094std::unique_ptr<ASTConsumer>
David Blaikie6beb6aa2014-08-10 19:56:51 +000095GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000096 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +000097 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
98 return nullptr;
99
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000100 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000101 std::unique_ptr<raw_pwrite_stream> OS =
Ilya Biryukov417085a2017-11-16 16:25:01 +0000102 CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000103 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000104 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000105
Douglas Gregorc567ba22011-07-22 16:35:34 +0000106 if (!CI.getFrontendOpts().RelocatablePCH)
107 Sysroot.clear();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000108
Hans Wennborg08c5a7b2018-06-25 13:23:49 +0000109 const auto &FrontendOpts = CI.getFrontendOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000110 auto Buffer = std::make_shared<PCHBuffer>();
111 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
112 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +0000113 CI.getPreprocessor(), OutputFile, Sysroot,
Hans Wennborg08c5a7b2018-06-25 13:23:49 +0000114 Buffer, FrontendOpts.ModuleFileExtensions,
115 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
116 FrontendOpts.IncludeTimestamps));
Adrian Prantl03914062015-09-18 22:10:59 +0000117 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000118 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000119
120 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000121}
122
Ilya Biryukov417085a2017-11-16 16:25:01 +0000123bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
124 std::string &Sysroot) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000125 Sysroot = CI.getHeaderSearchOpts().Sysroot;
126 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000127 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000128 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000129 }
130
Ilya Biryukov417085a2017-11-16 16:25:01 +0000131 return true;
132}
133
134std::unique_ptr<llvm::raw_pwrite_stream>
135GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
136 std::string &OutputFile) {
Daniel Dunbara2867c72011-01-31 22:00:44 +0000137 // We use createOutputFile here because this is exposed via libclang, and we
138 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000139 // We use a temporary to avoid race conditions.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000140 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000141 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
142 /*RemoveFileOnSignal=*/false, InFile,
143 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000144 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000145 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000146
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000147 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000148 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000149}
150
Argyrios Kyrtzidiscf486b22017-02-27 03:52:36 +0000151bool GeneratePCHAction::shouldEraseOutputFiles() {
152 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
153 return false;
154 return ASTFrontendAction::shouldEraseOutputFiles();
155}
156
Richard Smithd9259c22017-06-09 01:36:10 +0000157bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
Manman Renffd3e9d2017-01-09 19:20:18 +0000158 CI.getLangOpts().CompilingPCH = true;
159 return true;
160}
161
David Blaikie6beb6aa2014-08-10 19:56:51 +0000162std::unique_ptr<ASTConsumer>
163GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
164 StringRef InFile) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000165 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000166 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000167 return nullptr;
168
Richard Smithbbcc9f02016-08-26 00:14:38 +0000169 std::string OutputFile = CI.getFrontendOpts().OutputFile;
170 std::string Sysroot;
171
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000172 auto Buffer = std::make_shared<PCHBuffer>();
173 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000174
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000175 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +0000176 CI.getPreprocessor(), OutputFile, Sysroot,
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000177 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
178 /*AllowASTWithErrors=*/false,
179 /*IncludeTimestamps=*/
180 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000181 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000182 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000183 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000184}
185
Richard Smith1f2bd352017-07-06 21:05:56 +0000186bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
187 CompilerInstance &CI) {
188 if (!CI.getLangOpts().Modules) {
189 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
190 return false;
191 }
192
193 return GenerateModuleAction::BeginSourceFileAction(CI);
194}
195
Peter Collingbourne03f89072016-07-15 00:55:40 +0000196std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000197GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
198 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000199 // If no output file was provided, figure out where this module would go
200 // in the module cache.
201 if (CI.getFrontendOpts().OutputFile.empty()) {
Richard Smithf74d9462017-04-28 01:49:42 +0000202 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
203 if (ModuleMapFile.empty())
204 ModuleMapFile = InFile;
205
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000206 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000207 CI.getFrontendOpts().OutputFile =
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000208 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
209 ModuleMapFile);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000210 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000211
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000212 // We use createOutputFile here because this is exposed via libclang, and we
213 // must disable the RemoveFileOnSignal behavior.
214 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000215 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
216 /*RemoveFileOnSignal=*/false, InFile,
217 /*Extension=*/"", /*useTemporary=*/true,
218 /*CreateMissingDirectories=*/true);
219}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000220
Richard Smithd9259c22017-06-09 01:36:10 +0000221bool GenerateModuleInterfaceAction::BeginSourceFileAction(
222 CompilerInstance &CI) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000223 if (!CI.getLangOpts().ModulesTS) {
224 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
225 return false;
226 }
227
228 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
229
Richard Smithd9259c22017-06-09 01:36:10 +0000230 return GenerateModuleAction::BeginSourceFileAction(CI);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000231}
232
233std::unique_ptr<raw_pwrite_stream>
234GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
235 StringRef InFile) {
236 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000237}
238
Richard Smithd6509cf2018-09-15 01:21:15 +0000239bool GenerateHeaderModuleAction::PrepareToExecuteAction(
240 CompilerInstance &CI) {
241 if (!CI.getLangOpts().Modules && !CI.getLangOpts().ModulesTS) {
242 CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
243 return false;
244 }
245
246 auto &Inputs = CI.getFrontendOpts().Inputs;
247 if (Inputs.empty())
248 return GenerateModuleAction::BeginInvocation(CI);
249
250 auto Kind = Inputs[0].getKind();
251
252 // Convert the header file inputs into a single module input buffer.
253 SmallString<256> HeaderContents;
254 ModuleHeaders.reserve(Inputs.size());
255 for (const FrontendInputFile &FIF : Inputs) {
256 // FIXME: We should support re-compiling from an AST file.
257 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
258 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
259 << (FIF.isFile() ? FIF.getFile()
260 : FIF.getBuffer()->getBufferIdentifier());
261 return true;
262 }
263
264 HeaderContents += "#include \"";
265 HeaderContents += FIF.getFile();
266 HeaderContents += "\"\n";
267 ModuleHeaders.push_back(FIF.getFile());
268 }
269 Buffer = llvm::MemoryBuffer::getMemBufferCopy(
270 HeaderContents, Module::getModuleInputBufferName());
271
272 // Set that buffer up as our "real" input.
273 Inputs.clear();
274 Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false));
275
276 return GenerateModuleAction::PrepareToExecuteAction(CI);
277}
278
279bool GenerateHeaderModuleAction::BeginSourceFileAction(
280 CompilerInstance &CI) {
281 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
282
283 // Synthesize a Module object for the given headers.
284 auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
285 SmallVector<Module::Header, 16> Headers;
286 for (StringRef Name : ModuleHeaders) {
287 const DirectoryLookup *CurDir = nullptr;
288 const FileEntry *FE = HS.LookupFile(
289 Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir,
290 None, nullptr, nullptr, nullptr, nullptr, nullptr);
291 if (!FE) {
292 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
293 << Name;
294 continue;
295 }
296 Headers.push_back({Name, FE});
297 }
298 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
299
300 return GenerateModuleAction::BeginSourceFileAction(CI);
301}
302
303std::unique_ptr<raw_pwrite_stream>
304GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
305 StringRef InFile) {
306 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
307}
308
Etienne Bergeron98de8052016-05-12 19:51:18 +0000309SyntaxOnlyAction::~SyntaxOnlyAction() {
310}
311
David Blaikie6beb6aa2014-08-10 19:56:51 +0000312std::unique_ptr<ASTConsumer>
313SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
314 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000315}
316
David Blaikie6beb6aa2014-08-10 19:56:51 +0000317std::unique_ptr<ASTConsumer>
318DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
319 StringRef InFile) {
320 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000321}
322
David Blaikie6beb6aa2014-08-10 19:56:51 +0000323std::unique_ptr<ASTConsumer>
324VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
325 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000326}
327
328void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000329 CompilerInstance &CI = getCompilerInstance();
330 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
331 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000332 std::unique_ptr<ASTReader> Reader(new ASTReader(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000333 CI.getPreprocessor(), &CI.getASTContext(), CI.getPCHContainerReader(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000334 CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000335 Sysroot.empty() ? "" : Sysroot.c_str(),
336 /*DisableValidation*/ false,
337 /*AllowPCHWithCompilerErrors*/ false,
338 /*AllowConfigurationMismatch*/ true,
339 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000340
341 Reader->ReadAST(getCurrentFile(),
342 Preamble ? serialization::MK_Preamble
343 : serialization::MK_PCH,
344 SourceLocation(),
345 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000346}
347
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000348namespace {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000349struct TemplightEntry {
350 std::string Name;
351 std::string Kind;
352 std::string Event;
353 std::string DefinitionLocation;
354 std::string PointOfInstantiation;
355};
356} // namespace
357
358namespace llvm {
359namespace yaml {
360template <> struct MappingTraits<TemplightEntry> {
361 static void mapping(IO &io, TemplightEntry &fields) {
362 io.mapRequired("name", fields.Name);
363 io.mapRequired("kind", fields.Kind);
364 io.mapRequired("event", fields.Event);
365 io.mapRequired("orig", fields.DefinitionLocation);
366 io.mapRequired("poi", fields.PointOfInstantiation);
367 }
368};
369} // namespace yaml
370} // namespace llvm
371
372namespace {
373class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
374 using CodeSynthesisContext = Sema::CodeSynthesisContext;
375
376public:
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000377 void initialize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000378
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000379 void finalize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000380
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000381 void atTemplateBegin(const Sema &TheSema,
382 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000383 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
384 }
385
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000386 void atTemplateEnd(const Sema &TheSema,
387 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000388 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
389 }
390
391private:
392 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
393 switch (Kind) {
394 case CodeSynthesisContext::TemplateInstantiation:
395 return "TemplateInstantiation";
396 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
397 return "DefaultTemplateArgumentInstantiation";
398 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
399 return "DefaultFunctionArgumentInstantiation";
400 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
401 return "ExplicitTemplateArgumentSubstitution";
402 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
403 return "DeducedTemplateArgumentSubstitution";
404 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
405 return "PriorTemplateArgumentSubstitution";
406 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
407 return "DefaultTemplateArgumentChecking";
Richard Smith5159bbad2018-09-05 22:30:37 +0000408 case CodeSynthesisContext::ExceptionSpecEvaluation:
409 return "ExceptionSpecEvaluation";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000410 case CodeSynthesisContext::ExceptionSpecInstantiation:
411 return "ExceptionSpecInstantiation";
412 case CodeSynthesisContext::DeclaringSpecialMember:
413 return "DeclaringSpecialMember";
414 case CodeSynthesisContext::DefiningSynthesizedFunction:
415 return "DefiningSynthesizedFunction";
416 case CodeSynthesisContext::Memoization:
417 return "Memoization";
418 }
419 return "";
420 }
421
422 template <bool BeginInstantiation>
423 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
424 const CodeSynthesisContext &Inst) {
425 std::string YAML;
426 {
427 llvm::raw_string_ostream OS(YAML);
428 llvm::yaml::Output YO(OS);
429 TemplightEntry Entry =
430 getTemplightEntry<BeginInstantiation>(TheSema, Inst);
431 llvm::yaml::EmptyContext Context;
432 llvm::yaml::yamlize(YO, Entry, true, Context);
433 }
434 Out << "---" << YAML << "\n";
435 }
436
437 template <bool BeginInstantiation>
438 static TemplightEntry getTemplightEntry(const Sema &TheSema,
439 const CodeSynthesisContext &Inst) {
440 TemplightEntry Entry;
441 Entry.Kind = toString(Inst.Kind);
442 Entry.Event = BeginInstantiation ? "Begin" : "End";
443 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
444 llvm::raw_string_ostream OS(Entry.Name);
445 NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +0000446 const PresumedLoc DefLoc =
Gabor Horvath207e7b12018-02-10 14:04:45 +0000447 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
448 if(!DefLoc.isInvalid())
449 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
450 std::to_string(DefLoc.getLine()) + ":" +
451 std::to_string(DefLoc.getColumn());
452 }
453 const PresumedLoc PoiLoc =
454 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
455 if (!PoiLoc.isInvalid()) {
456 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
457 std::to_string(PoiLoc.getLine()) + ":" +
458 std::to_string(PoiLoc.getColumn());
459 }
460 return Entry;
461 }
462};
463} // namespace
464
465std::unique_ptr<ASTConsumer>
466TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
467 return llvm::make_unique<ASTConsumer>();
468}
469
470void TemplightDumpAction::ExecuteAction() {
471 CompilerInstance &CI = getCompilerInstance();
472
473 // This part is normally done by ASTFrontEndAction, but needs to happen
474 // before Templight observers can be created
475 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
476 // here so the source manager would be initialized.
477 EnsureSemaIsCreated(CI, *this);
478
479 CI.getSema().TemplateInstCallbacks.push_back(
480 llvm::make_unique<DefaultTemplateInstCallback>());
481 ASTFrontendAction::ExecuteAction();
482}
483
484namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000485 /// AST reader listener that dumps module information for a module
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000486 /// file.
487 class DumpModuleInfoListener : public ASTReaderListener {
488 llvm::raw_ostream &Out;
489
490 public:
491 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
492
493#define DUMP_BOOLEAN(Value, Text) \
494 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
495
Craig Topperafa7cb32014-03-13 06:07:04 +0000496 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000497 Out.indent(2)
498 << "Generated by "
499 << (FullVersion == getClangFullRepositoryVersion()? "this"
500 : "a different")
501 << " Clang: " << FullVersion << "\n";
502 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
503 }
504
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000505 void ReadModuleName(StringRef ModuleName) override {
506 Out.indent(2) << "Module name: " << ModuleName << "\n";
507 }
508 void ReadModuleMapFile(StringRef ModuleMapPath) override {
509 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
510 }
511
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000512 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
513 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000514 Out.indent(2) << "Language options:\n";
515#define LANGOPT(Name, Bits, Default, Description) \
516 DUMP_BOOLEAN(LangOpts.Name, Description);
517#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
518 Out.indent(4) << Description << ": " \
519 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
520#define VALUE_LANGOPT(Name, Bits, Default, Description) \
521 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
522#define BENIGN_LANGOPT(Name, Bits, Default, Description)
523#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
524#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000525
526 if (!LangOpts.ModuleFeatures.empty()) {
527 Out.indent(4) << "Module features:\n";
528 for (StringRef Feature : LangOpts.ModuleFeatures)
529 Out.indent(6) << Feature << "\n";
530 }
531
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000532 return false;
533 }
534
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000535 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
536 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000537 Out.indent(2) << "Target options:\n";
538 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
539 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
540 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000541
542 if (!TargetOpts.FeaturesAsWritten.empty()) {
543 Out.indent(4) << "Target features:\n";
544 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
545 I != N; ++I) {
546 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
547 }
548 }
549
550 return false;
551 }
552
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000553 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
554 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000555 Out.indent(2) << "Diagnostic options:\n";
556#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
557#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
558 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
559#define VALUE_DIAGOPT(Name, Bits, Default) \
560 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
561#include "clang/Basic/DiagnosticOptions.def"
562
Richard Smith3be1cb22014-08-07 00:24:21 +0000563 Out.indent(4) << "Diagnostic flags:\n";
564 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000565 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000566 for (const std::string &Remark : DiagOpts->Remarks)
567 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000568
569 return false;
570 }
571
Craig Topperafa7cb32014-03-13 06:07:04 +0000572 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000573 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000574 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000575 Out.indent(2) << "Header search options:\n";
576 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbdff27d2017-02-25 18:14:31 +0000577 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000578 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000579 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
580 "Use builtin include directories [-nobuiltininc]");
581 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
582 "Use standard system include directories [-nostdinc]");
583 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
584 "Use standard C++ include directories [-nostdinc++]");
585 DUMP_BOOLEAN(HSOpts.UseLibcxx,
586 "Use libc++ (rather than libstdc++) [-stdlib=]");
587 return false;
588 }
589
Craig Topperafa7cb32014-03-13 06:07:04 +0000590 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
591 bool Complain,
592 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000593 Out.indent(2) << "Preprocessor options:\n";
594 DUMP_BOOLEAN(PPOpts.UsePredefines,
595 "Uses compiler/target-specific predefines [-undef]");
596 DUMP_BOOLEAN(PPOpts.DetailedRecord,
597 "Uses detailed preprocessing record (for indexing)");
598
599 if (!PPOpts.Macros.empty()) {
600 Out.indent(4) << "Predefined macros:\n";
601 }
602
603 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
604 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
605 I != IEnd; ++I) {
606 Out.indent(6);
607 if (I->second)
608 Out << "-U";
609 else
610 Out << "-D";
611 Out << I->first << "\n";
612 }
613 return false;
614 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000615
616 /// Indicates that a particular module file extension has been read.
617 void readModuleFileExtension(
618 const ModuleFileExtensionMetadata &Metadata) override {
619 Out.indent(2) << "Module file extension '"
620 << Metadata.BlockName << "' " << Metadata.MajorVersion
621 << "." << Metadata.MinorVersion;
622 if (!Metadata.UserInfo.empty()) {
623 Out << ": ";
624 Out.write_escaped(Metadata.UserInfo);
625 }
626
627 Out << "\n";
628 }
Vassil Vassilev33eb7292018-07-18 06:49:33 +0000629
630 /// Tells the \c ASTReaderListener that we want to receive the
631 /// input files of the AST file via \c visitInputFile.
632 bool needsInputFileVisitation() override { return true; }
633
634 /// Tells the \c ASTReaderListener that we want to receive the
635 /// input files of the AST file via \c visitInputFile.
636 bool needsSystemInputFileVisitation() override { return true; }
637
638 /// Indicates that the AST file contains particular input file.
639 ///
640 /// \returns true to continue receiving the next input file, false to stop.
641 bool visitInputFile(StringRef Filename, bool isSystem,
642 bool isOverridden, bool isExplicitModule) override {
643
644 Out.indent(2) << "Input file: " << Filename;
645
646 if (isSystem || isOverridden || isExplicitModule) {
647 Out << " [";
648 if (isSystem) {
649 Out << "System";
650 if (isOverridden || isExplicitModule)
651 Out << ", ";
652 }
653 if (isOverridden) {
654 Out << "Overridden";
655 if (isExplicitModule)
656 Out << ", ";
657 }
658 if (isExplicitModule)
659 Out << "ExplicitModule";
660
661 Out << "]";
662 }
663
664 Out << "\n";
665
666 return true;
667 }
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +0000668
669 /// Returns true if this \c ASTReaderListener wants to receive the
670 /// imports of the AST file via \c visitImport, false otherwise.
671 bool needsImportVisitation() const override { return true; }
672
673 /// If needsImportVisitation returns \c true, this is called for each
674 /// AST file imported by this AST file.
675 void visitImport(StringRef ModuleName, StringRef Filename) override {
676 Out.indent(2) << "Imports module '" << ModuleName
677 << "': " << Filename.str() << "\n";
678 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000679#undef DUMP_BOOLEAN
680 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000681}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000682
Adrian Prantl576b2db2016-08-17 23:13:53 +0000683bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
684 // The Object file reader also supports raw ast files and there is no point in
685 // being strict about the module file format in -module-file-info mode.
686 CI.getHeaderSearchOpts().ModuleFormat = "obj";
687 return true;
688}
689
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000690void DumpModuleInfoAction::ExecuteAction() {
691 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000692 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000693 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
694 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000695 std::error_code EC;
696 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
697 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000698 }
699 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
700
701 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000702 auto &FileMgr = getCompilerInstance().getFileManager();
703 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
704 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
705 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
706 Magic[2] == 'C' && Magic[3] == 'H');
707 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000708
Manman Ren47a44452016-07-26 17:12:17 +0000709 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000710 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000711 HeaderSearchOptions &HSOpts =
712 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000713 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000714 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000715 /*FindModuleFileExtensions=*/true, Listener,
716 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000717}
718
Daniel Dunbar88357802009-11-14 10:42:57 +0000719//===----------------------------------------------------------------------===//
720// Preprocessor Actions
721//===----------------------------------------------------------------------===//
722
723void DumpRawTokensAction::ExecuteAction() {
724 Preprocessor &PP = getCompilerInstance().getPreprocessor();
725 SourceManager &SM = PP.getSourceManager();
726
727 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000728 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000730 RawLex.SetKeepWhitespaceMode(true);
731
732 Token RawTok;
733 RawLex.LexFromRawLexer(RawTok);
734 while (RawTok.isNot(tok::eof)) {
735 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000736 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000737 RawLex.LexFromRawLexer(RawTok);
738 }
739}
740
741void DumpTokensAction::ExecuteAction() {
742 Preprocessor &PP = getCompilerInstance().getPreprocessor();
743 // Start preprocessing the specified input file.
744 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000745 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000746 do {
747 PP.Lex(Tok);
748 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000749 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000750 } while (Tok.isNot(tok::eof));
751}
752
Daniel Dunbar88357802009-11-14 10:42:57 +0000753void PreprocessOnlyAction::ExecuteAction() {
754 Preprocessor &PP = getCompilerInstance().getPreprocessor();
755
Daniel Dunbard839e772010-06-11 20:10:12 +0000756 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000757 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000758
Daniel Dunbar88357802009-11-14 10:42:57 +0000759 Token Tok;
760 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000761 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000762 do {
763 PP.Lex(Tok);
764 } while (Tok.isNot(tok::eof));
765}
766
Daniel Dunbar88357802009-11-14 10:42:57 +0000767void PrintPreprocessedAction::ExecuteAction() {
768 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000769 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000770 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000771 //
772 // Look to see what type of line endings the file uses. If there's a
773 // CRLF, then we won't open the file up in binary mode. If there is
774 // just an LF or CR, then we will open the file up in binary mode.
775 // In this fashion, the output format should match the input format, unless
776 // the input format has inconsistent line endings.
777 //
778 // This should be a relatively fast operation since most files won't have
Fangrui Song6907ce22018-07-30 19:24:48 +0000779 // all of their source code on a single line. However, that is still a
Douglas Gregor52da28b2011-09-23 23:43:36 +0000780 // concern, so if we scan for too long, we'll just assume the file should
781 // be opened in binary mode.
782 bool BinaryMode = true;
783 bool InvalidFile = false;
784 const SourceManager& SM = CI.getSourceManager();
Fangrui Song6907ce22018-07-30 19:24:48 +0000785 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
Douglas Gregor52da28b2011-09-23 23:43:36 +0000786 &InvalidFile);
787 if (!InvalidFile) {
788 const char *cur = Buffer->getBufferStart();
789 const char *end = Buffer->getBufferEnd();
790 const char *next = (cur != end) ? cur + 1 : end;
791
792 // Limit ourselves to only scanning 256 characters into the source
Fangrui Song6907ce22018-07-30 19:24:48 +0000793 // file. This is mostly a sanity check in case the file has no
Douglas Gregor52da28b2011-09-23 23:43:36 +0000794 // newlines whatsoever.
795 if (end - cur > 256) end = cur + 256;
Aaron Ballman4fc36ae2017-06-16 20:52:59 +0000796
Douglas Gregor52da28b2011-09-23 23:43:36 +0000797 while (next < end) {
798 if (*cur == 0x0D) { // CR
799 if (*next == 0x0A) // CRLF
800 BinaryMode = false;
801
802 break;
803 } else if (*cur == 0x0A) // LF
804 break;
805
Richard Trieucc3949d2016-02-18 22:34:54 +0000806 ++cur;
807 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000808 }
809 }
810
Peter Collingbourne03f89072016-07-15 00:55:40 +0000811 std::unique_ptr<raw_ostream> OS =
Richard Smith8b464f22018-09-15 01:21:18 +0000812 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
Daniel Dunbar75546992009-12-03 09:13:30 +0000813 if (!OS) return;
814
Richard Smith8128f332017-05-05 22:18:51 +0000815 // If we're preprocessing a module map, start by dumping the contents of the
816 // module itself before switching to the input buffer.
817 auto &Input = getCurrentInput();
818 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
Richard Smithc784e962017-06-01 20:10:35 +0000819 if (Input.isFile()) {
820 (*OS) << "# 1 \"";
821 OS->write_escaped(Input.getFile());
822 (*OS) << "\"\n";
823 }
Richard Smith8128f332017-05-05 22:18:51 +0000824 getCurrentModule()->print(*OS);
825 (*OS) << "#pragma clang module contents\n";
826 }
827
Peter Collingbourne03f89072016-07-15 00:55:40 +0000828 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000829 CI.getPreprocessorOutputOpts());
830}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000831
832void PrintPreambleAction::ExecuteAction() {
Richard Smith40c0efa2017-04-26 18:57:40 +0000833 switch (getCurrentFileKind().getLanguage()) {
834 case InputKind::C:
835 case InputKind::CXX:
836 case InputKind::ObjC:
837 case InputKind::ObjCXX:
838 case InputKind::OpenCL:
839 case InputKind::CUDA:
Yaxun Liu887c5692018-04-25 01:10:37 +0000840 case InputKind::HIP:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000841 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000842
Richard Smith40c0efa2017-04-26 18:57:40 +0000843 case InputKind::Unknown:
844 case InputKind::Asm:
845 case InputKind::LLVM_IR:
846 case InputKind::RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000847 // We can't do anything with these.
848 return;
849 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000850
Richard Smith40c0efa2017-04-26 18:57:40 +0000851 // We don't expect to find any #include directives in a preprocessed input.
852 if (getCurrentFileKind().isPreprocessed())
853 return;
854
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000855 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000856 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
857 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000858 unsigned Preamble =
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000859 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
Benjamin Kramera8857962014-10-26 22:44:13 +0000860 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000861 }
862}
Aaron Ballman16ed8dd2018-05-31 13:57:09 +0000863
864void DumpCompilerOptionsAction::ExecuteAction() {
865 CompilerInstance &CI = getCompilerInstance();
866 std::unique_ptr<raw_ostream> OSP =
867 CI.createDefaultOutputFile(false, getCurrentFile());
868 if (!OSP)
869 return;
870
871 raw_ostream &OS = *OSP;
872 const Preprocessor &PP = CI.getPreprocessor();
873 const LangOptions &LangOpts = PP.getLangOpts();
874
875 // FIXME: Rather than manually format the JSON (which is awkward due to
876 // needing to remove trailing commas), this should make use of a JSON library.
877 // FIXME: Instead of printing enums as an integral value and specifying the
878 // type as a separate field, use introspection to print the enumerator.
879
880 OS << "{\n";
881 OS << "\n\"features\" : [\n";
882 {
883 llvm::SmallString<128> Str;
884#define FEATURE(Name, Predicate) \
885 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
886 .toVector(Str);
887#include "clang/Basic/Features.def"
888#undef FEATURE
889 // Remove the newline and comma from the last entry to ensure this remains
890 // valid JSON.
891 OS << Str.substr(0, Str.size() - 2);
892 }
893 OS << "\n],\n";
894
895 OS << "\n\"extensions\" : [\n";
896 {
897 llvm::SmallString<128> Str;
898#define EXTENSION(Name, Predicate) \
899 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
900 .toVector(Str);
901#include "clang/Basic/Features.def"
902#undef EXTENSION
903 // Remove the newline and comma from the last entry to ensure this remains
904 // valid JSON.
905 OS << Str.substr(0, Str.size() - 2);
906 }
907 OS << "\n]\n";
908
909 OS << "}";
910}