1//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This is the entry point to the clang -cc1 functionality, which implements the
10// core compiler functionality along with a number of additional tools for
11// demonstration and testing purposes.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Stack.h"
16#include "clang/Basic/TargetOptions.h"
17#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
18#include "clang/Config/config.h"
19#include "clang/Driver/DriverDiagnostic.h"
20#include "clang/Driver/Options.h"
21#include "clang/Frontend/CompilerInstance.h"
22#include "clang/Frontend/CompilerInvocation.h"
23#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticBuffer.h"
25#include "clang/Frontend/TextDiagnosticPrinter.h"
26#include "clang/Frontend/Utils.h"
27#include "clang/FrontendTool/Utils.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/LinkAllPasses.h"
31#include "llvm/MC/MCSubtargetInfo.h"
32#include "llvm/MC/TargetRegistry.h"
33#include "llvm/Option/Arg.h"
34#include "llvm/Option/ArgList.h"
35#include "llvm/Option/OptTable.h"
36#include "llvm/Support/BuryPointer.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Process.h"
42#include "llvm/Support/RISCVISAInfo.h"
43#include "llvm/Support/Signals.h"
44#include "llvm/Support/TargetSelect.h"
45#include "llvm/Support/TimeProfiler.h"
46#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/TargetParser/AArch64TargetParser.h"
50#include "llvm/TargetParser/ARMTargetParser.h"
51#include <cstdio>
52
53#ifdef CLANG_HAVE_RLIMITS
54#include <sys/resource.h>
55#endif
56
57using namespace clang;
58using namespace llvm::opt;
59
60//===----------------------------------------------------------------------===//
61// Main driver
62//===----------------------------------------------------------------------===//
63
64static void LLVMErrorHandler(void *UserData, const char *Message,
65 bool GenCrashDiag) {
66 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
67
68 Diags.Report(diag::err_fe_error_backend) << Message;
69
70 // Run the interrupt handlers to make sure any special cleanups get done, in
71 // particular that we remove files registered with RemoveFileOnSignal.
72 llvm::sys::RunInterruptHandlers();
73
74 // We cannot recover from llvm errors. When reporting a fatal error, exit
75 // with status 70 to generate crash diagnostics. For BSD systems this is
76 // defined as an internal software error. Otherwise, exit with status 1.
77 llvm::sys::Process::Exit(RetCode: GenCrashDiag ? 70 : 1);
78}
79
80#ifdef CLANG_HAVE_RLIMITS
81/// Attempt to ensure that we have at least 8MiB of usable stack space.
82static void ensureSufficientStack() {
83 struct rlimit rlim;
84 if (getrlimit(RLIMIT_STACK, rlimits: &rlim) != 0)
85 return;
86
87 // Increase the soft stack limit to our desired level, if necessary and
88 // possible.
89 if (rlim.rlim_cur != RLIM_INFINITY &&
90 rlim.rlim_cur < rlim_t(DesiredStackSize)) {
91 // Try to allocate sufficient stack.
92 if (rlim.rlim_max == RLIM_INFINITY ||
93 rlim.rlim_max >= rlim_t(DesiredStackSize))
94 rlim.rlim_cur = DesiredStackSize;
95 else if (rlim.rlim_cur == rlim.rlim_max)
96 return;
97 else
98 rlim.rlim_cur = rlim.rlim_max;
99
100 if (setrlimit(RLIMIT_STACK, rlimits: &rlim) != 0 ||
101 rlim.rlim_cur != DesiredStackSize)
102 return;
103 }
104}
105#else
106static void ensureSufficientStack() {}
107#endif
108
109/// Print supported cpus of the given target.
110static int PrintSupportedCPUs(std::string TargetStr) {
111 std::string Error;
112 const llvm::Target *TheTarget =
113 llvm::TargetRegistry::lookupTarget(Triple: TargetStr, Error);
114 if (!TheTarget) {
115 llvm::errs() << Error;
116 return 1;
117 }
118
119 // the target machine will handle the mcpu printing
120 llvm::TargetOptions Options;
121 std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
122 TheTarget->createTargetMachine(TT: TargetStr, CPU: "", Features: "+cpuhelp", Options,
123 RM: std::nullopt));
124 return 0;
125}
126
127static int PrintSupportedExtensions(std::string TargetStr) {
128 std::string Error;
129 const llvm::Target *TheTarget =
130 llvm::TargetRegistry::lookupTarget(Triple: TargetStr, Error);
131 if (!TheTarget) {
132 llvm::errs() << Error;
133 return 1;
134 }
135
136 llvm::TargetOptions Options;
137 std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
138 TheTarget->createTargetMachine(TT: TargetStr, CPU: "", Features: "", Options, RM: std::nullopt));
139 const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
140 const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
141 const llvm::ArrayRef<llvm::SubtargetFeatureKV> Features =
142 MCInfo->getAllProcessorFeatures();
143
144 llvm::StringMap<llvm::StringRef> DescMap;
145 for (const llvm::SubtargetFeatureKV &feature : Features)
146 DescMap.insert(KV: {feature.Key, feature.Desc});
147
148 if (MachineTriple.isRISCV())
149 llvm::riscvExtensionsHelp(DescMap);
150 else if (MachineTriple.isAArch64())
151 llvm::AArch64::PrintSupportedExtensions(DescMap);
152 else if (MachineTriple.isARM())
153 llvm::ARM::PrintSupportedExtensions(DescMap);
154 else {
155 // The option was already checked in Driver::HandleImmediateArgs,
156 // so we do not expect to get here if we are not a supported architecture.
157 assert(0 && "Unhandled triple for --print-supported-extensions option.");
158 return 1;
159 }
160
161 return 0;
162}
163
164int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
165 ensureSufficientStack();
166
167 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
168 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
169
170 // Register the support for object-file-wrapped Clang modules.
171 auto PCHOps = Clang->getPCHContainerOperations();
172 PCHOps->registerWriter(Writer: std::make_unique<ObjectFilePCHContainerWriter>());
173 PCHOps->registerReader(Reader: std::make_unique<ObjectFilePCHContainerReader>());
174
175 // Initialize targets first, so that --version shows registered targets.
176 llvm::InitializeAllTargets();
177 llvm::InitializeAllTargetMCs();
178 llvm::InitializeAllAsmPrinters();
179 llvm::InitializeAllAsmParsers();
180
181 // Buffer diagnostics from argument parsing so that we can output them using a
182 // well formed diagnostic object.
183 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
184 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
185 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
186
187 // Setup round-trip remarks for the DiagnosticsEngine used in CreateFromArgs.
188 if (find(Argv, StringRef("-Rround-trip-cc1-args")) != Argv.end())
189 Diags.setSeverity(diag::remark_cc1_round_trip_generated,
190 diag::Severity::Remark, {});
191
192 bool Success = CompilerInvocation::CreateFromArgs(Res&: Clang->getInvocation(),
193 CommandLineArgs: Argv, Diags, Argv0);
194
195 if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
196 llvm::timeTraceProfilerInitialize(
197 TimeTraceGranularity: Clang->getFrontendOpts().TimeTraceGranularity, ProcName: Argv0);
198 }
199 // --print-supported-cpus takes priority over the actual compilation.
200 if (Clang->getFrontendOpts().PrintSupportedCPUs)
201 return PrintSupportedCPUs(TargetStr: Clang->getTargetOpts().Triple);
202
203 // --print-supported-extensions takes priority over the actual compilation.
204 if (Clang->getFrontendOpts().PrintSupportedExtensions)
205 return PrintSupportedExtensions(TargetStr: Clang->getTargetOpts().Triple);
206
207 // Infer the builtin include path if unspecified.
208 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
209 Clang->getHeaderSearchOpts().ResourceDir.empty())
210 Clang->getHeaderSearchOpts().ResourceDir =
211 CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
212
213 // Create the actual diagnostics engine.
214 Clang->createDiagnostics();
215 if (!Clang->hasDiagnostics())
216 return 1;
217
218 // Set an error handler, so that any LLVM backend diagnostics go through our
219 // error handler.
220 llvm::install_fatal_error_handler(handler: LLVMErrorHandler,
221 user_data: static_cast<void*>(&Clang->getDiagnostics()));
222
223 DiagsBuffer->FlushDiagnostics(Diags&: Clang->getDiagnostics());
224 if (!Success) {
225 Clang->getDiagnosticClient().finish();
226 return 1;
227 }
228
229 // Execute the frontend actions.
230 {
231 llvm::TimeTraceScope TimeScope("ExecuteCompiler");
232 Success = ExecuteCompilerInvocation(Clang: Clang.get());
233 }
234
235 // If any timers were active but haven't been destroyed yet, print their
236 // results now. This happens in -disable-free mode.
237 llvm::TimerGroup::printAll(OS&: llvm::errs());
238 llvm::TimerGroup::clearAll();
239
240 if (llvm::timeTraceProfilerEnabled()) {
241 // It is possible that the compiler instance doesn't own a file manager here
242 // if we're compiling a module unit. Since the file manager are owned by AST
243 // when we're compiling a module unit. So the file manager may be invalid
244 // here.
245 //
246 // It should be fine to create file manager here since the file system
247 // options are stored in the compiler invocation and we can recreate the VFS
248 // from the compiler invocation.
249 if (!Clang->hasFileManager())
250 Clang->createFileManager(VFS: createVFSFromCompilerInvocation(
251 CI: Clang->getInvocation(), Diags&: Clang->getDiagnostics()));
252
253 if (auto profilerOutput = Clang->createOutputFile(
254 OutputPath: Clang->getFrontendOpts().TimeTracePath, /*Binary=*/false,
255 /*RemoveFileOnSignal=*/false,
256 /*useTemporary=*/UseTemporary: false)) {
257 llvm::timeTraceProfilerWrite(OS&: *profilerOutput);
258 profilerOutput.reset();
259 llvm::timeTraceProfilerCleanup();
260 Clang->clearOutputFiles(EraseFiles: false);
261 }
262 }
263
264 // Our error handler depends on the Diagnostics object, which we're
265 // potentially about to delete. Uninstall the handler now so that any
266 // later errors use the default handling behavior instead.
267 llvm::remove_fatal_error_handler();
268
269 // When running with -disable-free, don't do any destruction or shutdown.
270 if (Clang->getFrontendOpts().DisableFree) {
271 llvm::BuryPointer(Ptr: std::move(Clang));
272 return !Success;
273 }
274
275 return !Success;
276}
277

source code of clang/tools/driver/cc1_main.cpp