xref: /freebsd/contrib/llvm-project/clang/tools/driver/cc1_main.cpp (revision e40139ff33b48b56a24c808b166b04b8ee6f5b21)
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/Option/Arg.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Support/BuryPointer.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/TimeProfiler.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include <cstdio>
47 
48 #ifdef CLANG_HAVE_RLIMITS
49 #include <sys/resource.h>
50 #endif
51 
52 using namespace clang;
53 using namespace llvm::opt;
54 
55 //===----------------------------------------------------------------------===//
56 // Main driver
57 //===----------------------------------------------------------------------===//
58 
59 static void LLVMErrorHandler(void *UserData, const std::string &Message,
60                              bool GenCrashDiag) {
61   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
62 
63   Diags.Report(diag::err_fe_error_backend) << Message;
64 
65   // Run the interrupt handlers to make sure any special cleanups get done, in
66   // particular that we remove files registered with RemoveFileOnSignal.
67   llvm::sys::RunInterruptHandlers();
68 
69   // We cannot recover from llvm errors.  When reporting a fatal error, exit
70   // with status 70 to generate crash diagnostics.  For BSD systems this is
71   // defined as an internal software error.  Otherwise, exit with status 1.
72   exit(GenCrashDiag ? 70 : 1);
73 }
74 
75 #ifdef LINK_POLLY_INTO_TOOLS
76 namespace polly {
77 void initializePollyPasses(llvm::PassRegistry &Registry);
78 }
79 #endif
80 
81 #ifdef CLANG_HAVE_RLIMITS
82 #if defined(__linux__) && defined(__PIE__)
83 static size_t getCurrentStackAllocation() {
84   // If we can't compute the current stack usage, allow for 512K of command
85   // line arguments and environment.
86   size_t Usage = 512 * 1024;
87   if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
88     // We assume that the stack extends from its current address to the end of
89     // the environment space. In reality, there is another string literal (the
90     // program name) after the environment, but this is close enough (we only
91     // need to be within 100K or so).
92     unsigned long StackPtr, EnvEnd;
93     // Disable silly GCC -Wformat warning that complains about length
94     // modifiers on ignored format specifiers. We want to retain these
95     // for documentation purposes even though they have no effect.
96 #if defined(__GNUC__) && !defined(__clang__)
97 #pragma GCC diagnostic push
98 #pragma GCC diagnostic ignored "-Wformat"
99 #endif
100     if (fscanf(StatFile,
101                "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
102                "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
103                "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
104                "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
105                &StackPtr, &EnvEnd) == 2) {
106 #if defined(__GNUC__) && !defined(__clang__)
107 #pragma GCC diagnostic pop
108 #endif
109       Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
110     }
111     fclose(StatFile);
112   }
113   return Usage;
114 }
115 
116 #include <alloca.h>
117 
118 LLVM_ATTRIBUTE_NOINLINE
119 static void ensureStackAddressSpace() {
120   // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
121   // relatively close to the stack (they are only guaranteed to be 128MiB
122   // apart). This results in crashes if we happen to heap-allocate more than
123   // 128MiB before we reach our stack high-water mark.
124   //
125   // To avoid these crashes, ensure that we have sufficient virtual memory
126   // pages allocated before we start running.
127   size_t Curr = getCurrentStackAllocation();
128   const int kTargetStack = DesiredStackSize - 256 * 1024;
129   if (Curr < kTargetStack) {
130     volatile char *volatile Alloc =
131         static_cast<volatile char *>(alloca(kTargetStack - Curr));
132     Alloc[0] = 0;
133     Alloc[kTargetStack - Curr - 1] = 0;
134   }
135 }
136 #else
137 static void ensureStackAddressSpace() {}
138 #endif
139 
140 /// Attempt to ensure that we have at least 8MiB of usable stack space.
141 static void ensureSufficientStack() {
142   struct rlimit rlim;
143   if (getrlimit(RLIMIT_STACK, &rlim) != 0)
144     return;
145 
146   // Increase the soft stack limit to our desired level, if necessary and
147   // possible.
148   if (rlim.rlim_cur != RLIM_INFINITY &&
149       rlim.rlim_cur < rlim_t(DesiredStackSize)) {
150     // Try to allocate sufficient stack.
151     if (rlim.rlim_max == RLIM_INFINITY ||
152         rlim.rlim_max >= rlim_t(DesiredStackSize))
153       rlim.rlim_cur = DesiredStackSize;
154     else if (rlim.rlim_cur == rlim.rlim_max)
155       return;
156     else
157       rlim.rlim_cur = rlim.rlim_max;
158 
159     if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
160         rlim.rlim_cur != DesiredStackSize)
161       return;
162   }
163 
164   // We should now have a stack of size at least DesiredStackSize. Ensure
165   // that we can actually use that much, if necessary.
166   ensureStackAddressSpace();
167 }
168 #else
169 static void ensureSufficientStack() {}
170 #endif
171 
172 /// Print supported cpus of the given target.
173 static int PrintSupportedCPUs(std::string TargetStr) {
174   std::string Error;
175   const llvm::Target *TheTarget =
176       llvm::TargetRegistry::lookupTarget(TargetStr, Error);
177   if (!TheTarget) {
178     llvm::errs() << Error;
179     return 1;
180   }
181 
182   // the target machine will handle the mcpu printing
183   llvm::TargetOptions Options;
184   std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
185       TheTarget->createTargetMachine(TargetStr, "", "+cpuHelp", Options, None));
186   return 0;
187 }
188 
189 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
190   ensureSufficientStack();
191 
192   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
193   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
194 
195   // Register the support for object-file-wrapped Clang modules.
196   auto PCHOps = Clang->getPCHContainerOperations();
197   PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
198   PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
199 
200   // Initialize targets first, so that --version shows registered targets.
201   llvm::InitializeAllTargets();
202   llvm::InitializeAllTargetMCs();
203   llvm::InitializeAllAsmPrinters();
204   llvm::InitializeAllAsmParsers();
205 
206 #ifdef LINK_POLLY_INTO_TOOLS
207   llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
208   polly::initializePollyPasses(Registry);
209 #endif
210 
211   // Buffer diagnostics from argument parsing so that we can output them using a
212   // well formed diagnostic object.
213   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
214   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
215   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
216   bool Success =
217       CompilerInvocation::CreateFromArgs(Clang->getInvocation(), Argv, Diags);
218 
219   if (Clang->getFrontendOpts().TimeTrace) {
220     llvm::timeTraceProfilerInitialize(
221         Clang->getFrontendOpts().TimeTraceGranularity);
222   }
223   // --print-supported-cpus takes priority over the actual compilation.
224   if (Clang->getFrontendOpts().PrintSupportedCPUs)
225     return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
226 
227   // Infer the builtin include path if unspecified.
228   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
229       Clang->getHeaderSearchOpts().ResourceDir.empty())
230     Clang->getHeaderSearchOpts().ResourceDir =
231       CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
232 
233   // Create the actual diagnostics engine.
234   Clang->createDiagnostics();
235   if (!Clang->hasDiagnostics())
236     return 1;
237 
238   // Set an error handler, so that any LLVM backend diagnostics go through our
239   // error handler.
240   llvm::install_fatal_error_handler(LLVMErrorHandler,
241                                   static_cast<void*>(&Clang->getDiagnostics()));
242 
243   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
244   if (!Success)
245     return 1;
246 
247   // Execute the frontend actions.
248   {
249     llvm::TimeTraceScope TimeScope("ExecuteCompiler", StringRef(""));
250     Success = ExecuteCompilerInvocation(Clang.get());
251   }
252 
253   // If any timers were active but haven't been destroyed yet, print their
254   // results now.  This happens in -disable-free mode.
255   llvm::TimerGroup::printAll(llvm::errs());
256   llvm::TimerGroup::clearAll();
257 
258   if (llvm::timeTraceProfilerEnabled()) {
259     SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
260     llvm::sys::path::replace_extension(Path, "json");
261     if (auto profilerOutput =
262             Clang->createOutputFile(Path.str(),
263                                     /*Binary=*/false,
264                                     /*RemoveFileOnSignal=*/false, "",
265                                     /*Extension=*/"json",
266                                     /*useTemporary=*/false)) {
267 
268       llvm::timeTraceProfilerWrite(*profilerOutput);
269       // FIXME(ibiryukov): make profilerOutput flush in destructor instead.
270       profilerOutput->flush();
271       llvm::timeTraceProfilerCleanup();
272     }
273   }
274 
275   // Our error handler depends on the Diagnostics object, which we're
276   // potentially about to delete. Uninstall the handler now so that any
277   // later errors use the default handling behavior instead.
278   llvm::remove_fatal_error_handler();
279 
280   // When running with -disable-free, don't do any destruction or shutdown.
281   if (Clang->getFrontendOpts().DisableFree) {
282     llvm::BuryPointer(std::move(Clang));
283     return !Success;
284   }
285 
286   return !Success;
287 }
288