blob: 5ad9a1cc036b71a17dbb69862be14f31d4a8194c [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000019#include "clang/Lex/PreprocessorOptions.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000020#include "clang/Sema/TemplateInstCallback.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000021#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000022#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000023#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000024#include "llvm/Support/MemoryBuffer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000025#include "llvm/Support/Path.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000026#include "llvm/Support/raw_ostream.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000027#include "llvm/Support/YAMLTraits.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000028#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000029#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000030
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000031using namespace clang;
32
Gabor Horvath207e7b12018-02-10 14:04:45 +000033namespace {
34CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
35 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
36 : nullptr;
37}
38
39void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
40 if (Action.hasCodeCompletionSupport() &&
41 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
42 CI.createCodeCompletionConsumer();
43
44 if (!CI.hasSema())
45 CI.createSema(Action.getTranslationUnitKind(),
46 GetCodeCompletionConsumer(CI));
47}
48} // namespace
49
Daniel Dunbar88357802009-11-14 10:42:57 +000050//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000051// Custom Actions
52//===----------------------------------------------------------------------===//
53
David Blaikie6beb6aa2014-08-10 19:56:51 +000054std::unique_ptr<ASTConsumer>
55InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
56 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000057}
58
59void InitOnlyAction::ExecuteAction() {
60}
61
62//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000063// AST Consumer Actions
64//===----------------------------------------------------------------------===//
65
David Blaikie6beb6aa2014-08-10 19:56:51 +000066std::unique_ptr<ASTConsumer>
67ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Peter Collingbourne03f89072016-07-15 00:55:40 +000068 if (std::unique_ptr<raw_ostream> OS =
69 CI.createDefaultOutputFile(false, InFile))
70 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000071 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000072}
73
David Blaikie6beb6aa2014-08-10 19:56:51 +000074std::unique_ptr<ASTConsumer>
75ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienkod10d7902018-04-06 13:01:12 +000076 return CreateASTDumper(nullptr /*Dump to stdout.*/,
77 CI.getFrontendOpts().ASTDumpFilter,
Richard Smith35f986d2014-08-11 22:11:07 +000078 CI.getFrontendOpts().ASTDumpDecls,
Richard Smith3a36ac12017-03-09 22:00:01 +000079 CI.getFrontendOpts().ASTDumpAll,
Richard Smith6ea05822013-06-24 01:45:33 +000080 CI.getFrontendOpts().ASTDumpLookups);
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,
115 FrontendOpts.IncludeTimestamps));
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,
142 /*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=*/
179 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000180 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000181 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000182 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000183}
184
Richard Smith1f2bd352017-07-06 21:05:56 +0000185bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
186 CompilerInstance &CI) {
187 if (!CI.getLangOpts().Modules) {
188 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
189 return false;
190 }
191
192 return GenerateModuleAction::BeginSourceFileAction(CI);
193}
194
Peter Collingbourne03f89072016-07-15 00:55:40 +0000195std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000196GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
197 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000198 // If no output file was provided, figure out where this module would go
199 // in the module cache.
200 if (CI.getFrontendOpts().OutputFile.empty()) {
Richard Smithf74d9462017-04-28 01:49:42 +0000201 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
202 if (ModuleMapFile.empty())
203 ModuleMapFile = InFile;
204
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000205 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000206 CI.getFrontendOpts().OutputFile =
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000207 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
208 ModuleMapFile);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000209 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000210
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000211 // We use createOutputFile here because this is exposed via libclang, and we
212 // must disable the RemoveFileOnSignal behavior.
213 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000214 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
215 /*RemoveFileOnSignal=*/false, InFile,
216 /*Extension=*/"", /*useTemporary=*/true,
217 /*CreateMissingDirectories=*/true);
218}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000219
Richard Smithd9259c22017-06-09 01:36:10 +0000220bool GenerateModuleInterfaceAction::BeginSourceFileAction(
221 CompilerInstance &CI) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000222 if (!CI.getLangOpts().ModulesTS) {
223 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
224 return false;
225 }
226
227 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
228
Richard Smithd9259c22017-06-09 01:36:10 +0000229 return GenerateModuleAction::BeginSourceFileAction(CI);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000230}
231
232std::unique_ptr<raw_pwrite_stream>
233GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
234 StringRef InFile) {
235 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000236}
237
Richard Smithd6509cf2018-09-15 01:21:15 +0000238bool GenerateHeaderModuleAction::PrepareToExecuteAction(
239 CompilerInstance &CI) {
240 if (!CI.getLangOpts().Modules && !CI.getLangOpts().ModulesTS) {
241 CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
242 return false;
243 }
244
245 auto &Inputs = CI.getFrontendOpts().Inputs;
246 if (Inputs.empty())
247 return GenerateModuleAction::BeginInvocation(CI);
248
249 auto Kind = Inputs[0].getKind();
250
251 // Convert the header file inputs into a single module input buffer.
252 SmallString<256> HeaderContents;
253 ModuleHeaders.reserve(Inputs.size());
254 for (const FrontendInputFile &FIF : Inputs) {
255 // FIXME: We should support re-compiling from an AST file.
256 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
257 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
258 << (FIF.isFile() ? FIF.getFile()
259 : FIF.getBuffer()->getBufferIdentifier());
260 return true;
261 }
262
263 HeaderContents += "#include \"";
264 HeaderContents += FIF.getFile();
265 HeaderContents += "\"\n";
266 ModuleHeaders.push_back(FIF.getFile());
267 }
268 Buffer = llvm::MemoryBuffer::getMemBufferCopy(
269 HeaderContents, Module::getModuleInputBufferName());
270
271 // Set that buffer up as our "real" input.
272 Inputs.clear();
273 Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false));
274
275 return GenerateModuleAction::PrepareToExecuteAction(CI);
276}
277
278bool GenerateHeaderModuleAction::BeginSourceFileAction(
279 CompilerInstance &CI) {
280 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
281
282 // Synthesize a Module object for the given headers.
283 auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
284 SmallVector<Module::Header, 16> Headers;
285 for (StringRef Name : ModuleHeaders) {
286 const DirectoryLookup *CurDir = nullptr;
287 const FileEntry *FE = HS.LookupFile(
288 Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000289 None, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
Richard Smithd6509cf2018-09-15 01:21:15 +0000290 if (!FE) {
291 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
292 << Name;
293 continue;
294 }
295 Headers.push_back({Name, FE});
296 }
297 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
298
299 return GenerateModuleAction::BeginSourceFileAction(CI);
300}
301
302std::unique_ptr<raw_pwrite_stream>
303GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
304 StringRef InFile) {
305 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
306}
307
Etienne Bergeron98de8052016-05-12 19:51:18 +0000308SyntaxOnlyAction::~SyntaxOnlyAction() {
309}
310
David Blaikie6beb6aa2014-08-10 19:56:51 +0000311std::unique_ptr<ASTConsumer>
312SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
313 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000314}
315
David Blaikie6beb6aa2014-08-10 19:56:51 +0000316std::unique_ptr<ASTConsumer>
317DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
318 StringRef InFile) {
319 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000320}
321
David Blaikie6beb6aa2014-08-10 19:56:51 +0000322std::unique_ptr<ASTConsumer>
323VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
324 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000325}
326
327void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000328 CompilerInstance &CI = getCompilerInstance();
329 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
330 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000331 std::unique_ptr<ASTReader> Reader(new ASTReader(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000332 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
333 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000334 Sysroot.empty() ? "" : Sysroot.c_str(),
335 /*DisableValidation*/ false,
336 /*AllowPCHWithCompilerErrors*/ false,
337 /*AllowConfigurationMismatch*/ true,
338 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000339
340 Reader->ReadAST(getCurrentFile(),
341 Preamble ? serialization::MK_Preamble
342 : serialization::MK_PCH,
343 SourceLocation(),
344 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000345}
346
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000347namespace {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000348struct TemplightEntry {
349 std::string Name;
350 std::string Kind;
351 std::string Event;
352 std::string DefinitionLocation;
353 std::string PointOfInstantiation;
354};
355} // namespace
356
357namespace llvm {
358namespace yaml {
359template <> struct MappingTraits<TemplightEntry> {
360 static void mapping(IO &io, TemplightEntry &fields) {
361 io.mapRequired("name", fields.Name);
362 io.mapRequired("kind", fields.Kind);
363 io.mapRequired("event", fields.Event);
364 io.mapRequired("orig", fields.DefinitionLocation);
365 io.mapRequired("poi", fields.PointOfInstantiation);
366 }
367};
368} // namespace yaml
369} // namespace llvm
370
371namespace {
372class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
373 using CodeSynthesisContext = Sema::CodeSynthesisContext;
374
375public:
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000376 void initialize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000377
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000378 void finalize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000379
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000380 void atTemplateBegin(const Sema &TheSema,
381 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000382 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
383 }
384
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000385 void atTemplateEnd(const Sema &TheSema,
386 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000387 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
388 }
389
390private:
391 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
392 switch (Kind) {
393 case CodeSynthesisContext::TemplateInstantiation:
394 return "TemplateInstantiation";
395 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
396 return "DefaultTemplateArgumentInstantiation";
397 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
398 return "DefaultFunctionArgumentInstantiation";
399 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
400 return "ExplicitTemplateArgumentSubstitution";
401 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
402 return "DeducedTemplateArgumentSubstitution";
403 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
404 return "PriorTemplateArgumentSubstitution";
405 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
406 return "DefaultTemplateArgumentChecking";
Richard Smith5159bbad2018-09-05 22:30:37 +0000407 case CodeSynthesisContext::ExceptionSpecEvaluation:
408 return "ExceptionSpecEvaluation";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000409 case CodeSynthesisContext::ExceptionSpecInstantiation:
410 return "ExceptionSpecInstantiation";
411 case CodeSynthesisContext::DeclaringSpecialMember:
412 return "DeclaringSpecialMember";
413 case CodeSynthesisContext::DefiningSynthesizedFunction:
414 return "DefiningSynthesizedFunction";
415 case CodeSynthesisContext::Memoization:
416 return "Memoization";
417 }
418 return "";
419 }
420
421 template <bool BeginInstantiation>
422 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
423 const CodeSynthesisContext &Inst) {
424 std::string YAML;
425 {
426 llvm::raw_string_ostream OS(YAML);
427 llvm::yaml::Output YO(OS);
428 TemplightEntry Entry =
429 getTemplightEntry<BeginInstantiation>(TheSema, Inst);
430 llvm::yaml::EmptyContext Context;
431 llvm::yaml::yamlize(YO, Entry, true, Context);
432 }
433 Out << "---" << YAML << "\n";
434 }
435
436 template <bool BeginInstantiation>
437 static TemplightEntry getTemplightEntry(const Sema &TheSema,
438 const CodeSynthesisContext &Inst) {
439 TemplightEntry Entry;
440 Entry.Kind = toString(Inst.Kind);
441 Entry.Event = BeginInstantiation ? "Begin" : "End";
442 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
443 llvm::raw_string_ostream OS(Entry.Name);
444 NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +0000445 const PresumedLoc DefLoc =
Gabor Horvath207e7b12018-02-10 14:04:45 +0000446 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
447 if(!DefLoc.isInvalid())
448 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
449 std::to_string(DefLoc.getLine()) + ":" +
450 std::to_string(DefLoc.getColumn());
451 }
452 const PresumedLoc PoiLoc =
453 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
454 if (!PoiLoc.isInvalid()) {
455 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
456 std::to_string(PoiLoc.getLine()) + ":" +
457 std::to_string(PoiLoc.getColumn());
458 }
459 return Entry;
460 }
461};
462} // namespace
463
464std::unique_ptr<ASTConsumer>
465TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
466 return llvm::make_unique<ASTConsumer>();
467}
468
469void TemplightDumpAction::ExecuteAction() {
470 CompilerInstance &CI = getCompilerInstance();
471
472 // This part is normally done by ASTFrontEndAction, but needs to happen
473 // before Templight observers can be created
474 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
475 // here so the source manager would be initialized.
476 EnsureSemaIsCreated(CI, *this);
477
478 CI.getSema().TemplateInstCallbacks.push_back(
479 llvm::make_unique<DefaultTemplateInstCallback>());
480 ASTFrontendAction::ExecuteAction();
481}
482
483namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000484 /// AST reader listener that dumps module information for a module
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000485 /// file.
486 class DumpModuleInfoListener : public ASTReaderListener {
487 llvm::raw_ostream &Out;
488
489 public:
490 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
491
492#define DUMP_BOOLEAN(Value, Text) \
493 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
494
Craig Topperafa7cb32014-03-13 06:07:04 +0000495 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000496 Out.indent(2)
497 << "Generated by "
498 << (FullVersion == getClangFullRepositoryVersion()? "this"
499 : "a different")
500 << " Clang: " << FullVersion << "\n";
501 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
502 }
503
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000504 void ReadModuleName(StringRef ModuleName) override {
505 Out.indent(2) << "Module name: " << ModuleName << "\n";
506 }
507 void ReadModuleMapFile(StringRef ModuleMapPath) override {
508 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
509 }
510
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000511 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
512 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000513 Out.indent(2) << "Language options:\n";
514#define LANGOPT(Name, Bits, Default, Description) \
515 DUMP_BOOLEAN(LangOpts.Name, Description);
516#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
517 Out.indent(4) << Description << ": " \
518 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
519#define VALUE_LANGOPT(Name, Bits, Default, Description) \
520 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
521#define BENIGN_LANGOPT(Name, Bits, Default, Description)
522#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
523#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000524
525 if (!LangOpts.ModuleFeatures.empty()) {
526 Out.indent(4) << "Module features:\n";
527 for (StringRef Feature : LangOpts.ModuleFeatures)
528 Out.indent(6) << Feature << "\n";
529 }
530
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000531 return false;
532 }
533
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000534 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
535 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000536 Out.indent(2) << "Target options:\n";
537 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
538 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
539 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000540
541 if (!TargetOpts.FeaturesAsWritten.empty()) {
542 Out.indent(4) << "Target features:\n";
543 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
544 I != N; ++I) {
545 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
546 }
547 }
548
549 return false;
550 }
551
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000552 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
553 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000554 Out.indent(2) << "Diagnostic options:\n";
555#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
556#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
557 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
558#define VALUE_DIAGOPT(Name, Bits, Default) \
559 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
560#include "clang/Basic/DiagnosticOptions.def"
561
Richard Smith3be1cb22014-08-07 00:24:21 +0000562 Out.indent(4) << "Diagnostic flags:\n";
563 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000564 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000565 for (const std::string &Remark : DiagOpts->Remarks)
566 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000567
568 return false;
569 }
570
Craig Topperafa7cb32014-03-13 06:07:04 +0000571 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000572 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000573 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000574 Out.indent(2) << "Header search options:\n";
575 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbdff27d2017-02-25 18:14:31 +0000576 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000577 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000578 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
579 "Use builtin include directories [-nobuiltininc]");
580 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
581 "Use standard system include directories [-nostdinc]");
582 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
583 "Use standard C++ include directories [-nostdinc++]");
584 DUMP_BOOLEAN(HSOpts.UseLibcxx,
585 "Use libc++ (rather than libstdc++) [-stdlib=]");
586 return false;
587 }
588
Craig Topperafa7cb32014-03-13 06:07:04 +0000589 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
590 bool Complain,
591 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000592 Out.indent(2) << "Preprocessor options:\n";
593 DUMP_BOOLEAN(PPOpts.UsePredefines,
594 "Uses compiler/target-specific predefines [-undef]");
595 DUMP_BOOLEAN(PPOpts.DetailedRecord,
596 "Uses detailed preprocessing record (for indexing)");
597
598 if (!PPOpts.Macros.empty()) {
599 Out.indent(4) << "Predefined macros:\n";
600 }
601
602 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
603 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
604 I != IEnd; ++I) {
605 Out.indent(6);
606 if (I->second)
607 Out << "-U";
608 else
609 Out << "-D";
610 Out << I->first << "\n";
611 }
612 return false;
613 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000614
615 /// Indicates that a particular module file extension has been read.
616 void readModuleFileExtension(
617 const ModuleFileExtensionMetadata &Metadata) override {
618 Out.indent(2) << "Module file extension '"
619 << Metadata.BlockName << "' " << Metadata.MajorVersion
620 << "." << Metadata.MinorVersion;
621 if (!Metadata.UserInfo.empty()) {
622 Out << ": ";
623 Out.write_escaped(Metadata.UserInfo);
624 }
625
626 Out << "\n";
627 }
Vassil Vassilev33eb7292018-07-18 06:49:33 +0000628
629 /// Tells the \c ASTReaderListener that we want to receive the
630 /// input files of the AST file via \c visitInputFile.
631 bool needsInputFileVisitation() override { return true; }
632
633 /// Tells the \c ASTReaderListener that we want to receive the
634 /// input files of the AST file via \c visitInputFile.
635 bool needsSystemInputFileVisitation() override { return true; }
636
637 /// Indicates that the AST file contains particular input file.
638 ///
639 /// \returns true to continue receiving the next input file, false to stop.
640 bool visitInputFile(StringRef Filename, bool isSystem,
641 bool isOverridden, bool isExplicitModule) override {
642
643 Out.indent(2) << "Input file: " << Filename;
644
645 if (isSystem || isOverridden || isExplicitModule) {
646 Out << " [";
647 if (isSystem) {
648 Out << "System";
649 if (isOverridden || isExplicitModule)
650 Out << ", ";
651 }
652 if (isOverridden) {
653 Out << "Overridden";
654 if (isExplicitModule)
655 Out << ", ";
656 }
657 if (isExplicitModule)
658 Out << "ExplicitModule";
659
660 Out << "]";
661 }
662
663 Out << "\n";
664
665 return true;
666 }
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +0000667
668 /// Returns true if this \c ASTReaderListener wants to receive the
669 /// imports of the AST file via \c visitImport, false otherwise.
670 bool needsImportVisitation() const override { return true; }
671
672 /// If needsImportVisitation returns \c true, this is called for each
673 /// AST file imported by this AST file.
674 void visitImport(StringRef ModuleName, StringRef Filename) override {
675 Out.indent(2) << "Imports module '" << ModuleName
676 << "': " << Filename.str() << "\n";
677 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000678#undef DUMP_BOOLEAN
679 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000680}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000681
Adrian Prantl576b2db2016-08-17 23:13:53 +0000682bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
683 // The Object file reader also supports raw ast files and there is no point in
684 // being strict about the module file format in -module-file-info mode.
685 CI.getHeaderSearchOpts().ModuleFormat = "obj";
686 return true;
687}
688
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000689void DumpModuleInfoAction::ExecuteAction() {
690 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000691 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000692 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
693 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000694 std::error_code EC;
695 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
696 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000697 }
698 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
699
700 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000701 auto &FileMgr = getCompilerInstance().getFileManager();
702 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
703 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
704 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
705 Magic[2] == 'C' && Magic[3] == 'H');
706 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000707
Manman Ren47a44452016-07-26 17:12:17 +0000708 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000709 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000710 HeaderSearchOptions &HSOpts =
711 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000712 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000713 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000714 /*FindModuleFileExtensions=*/true, Listener,
715 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000716}
717
Daniel Dunbar88357802009-11-14 10:42:57 +0000718//===----------------------------------------------------------------------===//
719// Preprocessor Actions
720//===----------------------------------------------------------------------===//
721
722void DumpRawTokensAction::ExecuteAction() {
723 Preprocessor &PP = getCompilerInstance().getPreprocessor();
724 SourceManager &SM = PP.getSourceManager();
725
726 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000727 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000728 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000729 RawLex.SetKeepWhitespaceMode(true);
730
731 Token RawTok;
732 RawLex.LexFromRawLexer(RawTok);
733 while (RawTok.isNot(tok::eof)) {
734 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000735 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000736 RawLex.LexFromRawLexer(RawTok);
737 }
738}
739
740void DumpTokensAction::ExecuteAction() {
741 Preprocessor &PP = getCompilerInstance().getPreprocessor();
742 // Start preprocessing the specified input file.
743 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000744 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000745 do {
746 PP.Lex(Tok);
747 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000748 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000749 } while (Tok.isNot(tok::eof));
750}
751
Daniel Dunbar88357802009-11-14 10:42:57 +0000752void PreprocessOnlyAction::ExecuteAction() {
753 Preprocessor &PP = getCompilerInstance().getPreprocessor();
754
Daniel Dunbard839e772010-06-11 20:10:12 +0000755 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000756 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000757
Daniel Dunbar88357802009-11-14 10:42:57 +0000758 Token Tok;
759 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000760 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000761 do {
762 PP.Lex(Tok);
763 } while (Tok.isNot(tok::eof));
764}
765
Daniel Dunbar88357802009-11-14 10:42:57 +0000766void PrintPreprocessedAction::ExecuteAction() {
767 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000768 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000769 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000770 //
771 // Look to see what type of line endings the file uses. If there's a
772 // CRLF, then we won't open the file up in binary mode. If there is
773 // just an LF or CR, then we will open the file up in binary mode.
774 // In this fashion, the output format should match the input format, unless
775 // the input format has inconsistent line endings.
776 //
777 // This should be a relatively fast operation since most files won't have
Fangrui Song6907ce22018-07-30 19:24:48 +0000778 // all of their source code on a single line. However, that is still a
Douglas Gregor52da28b2011-09-23 23:43:36 +0000779 // concern, so if we scan for too long, we'll just assume the file should
780 // be opened in binary mode.
781 bool BinaryMode = true;
782 bool InvalidFile = false;
783 const SourceManager& SM = CI.getSourceManager();
Fangrui Song6907ce22018-07-30 19:24:48 +0000784 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
Douglas Gregor52da28b2011-09-23 23:43:36 +0000785 &InvalidFile);
786 if (!InvalidFile) {
787 const char *cur = Buffer->getBufferStart();
788 const char *end = Buffer->getBufferEnd();
789 const char *next = (cur != end) ? cur + 1 : end;
790
791 // Limit ourselves to only scanning 256 characters into the source
Fangrui Song6907ce22018-07-30 19:24:48 +0000792 // file. This is mostly a sanity check in case the file has no
Douglas Gregor52da28b2011-09-23 23:43:36 +0000793 // newlines whatsoever.
794 if (end - cur > 256) end = cur + 256;
Aaron Ballman4fc36ae2017-06-16 20:52:59 +0000795
Douglas Gregor52da28b2011-09-23 23:43:36 +0000796 while (next < end) {
797 if (*cur == 0x0D) { // CR
798 if (*next == 0x0A) // CRLF
799 BinaryMode = false;
800
801 break;
802 } else if (*cur == 0x0A) // LF
803 break;
804
Richard Trieucc3949d2016-02-18 22:34:54 +0000805 ++cur;
806 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000807 }
808 }
809
Peter Collingbourne03f89072016-07-15 00:55:40 +0000810 std::unique_ptr<raw_ostream> OS =
Richard Smith8b464f22018-09-15 01:21:18 +0000811 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
Daniel Dunbar75546992009-12-03 09:13:30 +0000812 if (!OS) return;
813
Richard Smith8128f332017-05-05 22:18:51 +0000814 // If we're preprocessing a module map, start by dumping the contents of the
815 // module itself before switching to the input buffer.
816 auto &Input = getCurrentInput();
817 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
Richard Smithc784e962017-06-01 20:10:35 +0000818 if (Input.isFile()) {
819 (*OS) << "# 1 \"";
820 OS->write_escaped(Input.getFile());
821 (*OS) << "\"\n";
822 }
Richard Smith8128f332017-05-05 22:18:51 +0000823 getCurrentModule()->print(*OS);
824 (*OS) << "#pragma clang module contents\n";
825 }
826
Peter Collingbourne03f89072016-07-15 00:55:40 +0000827 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000828 CI.getPreprocessorOutputOpts());
829}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000830
831void PrintPreambleAction::ExecuteAction() {
Richard Smith40c0efa2017-04-26 18:57:40 +0000832 switch (getCurrentFileKind().getLanguage()) {
833 case InputKind::C:
834 case InputKind::CXX:
835 case InputKind::ObjC:
836 case InputKind::ObjCXX:
837 case InputKind::OpenCL:
838 case InputKind::CUDA:
Yaxun Liu887c5692018-04-25 01:10:37 +0000839 case InputKind::HIP:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000840 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000841
Richard Smith40c0efa2017-04-26 18:57:40 +0000842 case InputKind::Unknown:
843 case InputKind::Asm:
844 case InputKind::LLVM_IR:
845 case InputKind::RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000846 // We can't do anything with these.
847 return;
848 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000849
Richard Smith40c0efa2017-04-26 18:57:40 +0000850 // We don't expect to find any #include directives in a preprocessed input.
851 if (getCurrentFileKind().isPreprocessed())
852 return;
853
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000854 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000855 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
856 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000857 unsigned Preamble =
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000858 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
Benjamin Kramera8857962014-10-26 22:44:13 +0000859 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000860 }
861}
Aaron Ballman16ed8dd2018-05-31 13:57:09 +0000862
863void DumpCompilerOptionsAction::ExecuteAction() {
864 CompilerInstance &CI = getCompilerInstance();
865 std::unique_ptr<raw_ostream> OSP =
866 CI.createDefaultOutputFile(false, getCurrentFile());
867 if (!OSP)
868 return;
869
870 raw_ostream &OS = *OSP;
871 const Preprocessor &PP = CI.getPreprocessor();
872 const LangOptions &LangOpts = PP.getLangOpts();
873
874 // FIXME: Rather than manually format the JSON (which is awkward due to
875 // needing to remove trailing commas), this should make use of a JSON library.
876 // FIXME: Instead of printing enums as an integral value and specifying the
877 // type as a separate field, use introspection to print the enumerator.
878
879 OS << "{\n";
880 OS << "\n\"features\" : [\n";
881 {
882 llvm::SmallString<128> Str;
883#define FEATURE(Name, Predicate) \
884 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
885 .toVector(Str);
886#include "clang/Basic/Features.def"
887#undef FEATURE
888 // Remove the newline and comma from the last entry to ensure this remains
889 // valid JSON.
890 OS << Str.substr(0, Str.size() - 2);
891 }
892 OS << "\n],\n";
893
894 OS << "\n\"extensions\" : [\n";
895 {
896 llvm::SmallString<128> Str;
897#define EXTENSION(Name, Predicate) \
898 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
899 .toVector(Str);
900#include "clang/Basic/Features.def"
901#undef EXTENSION
902 // Remove the newline and comma from the last entry to ensure this remains
903 // valid JSON.
904 OS << Str.substr(0, Str.size() - 2);
905 }
906 OS << "\n]\n";
907
908 OS << "}";
909}