Loading...
Searching...
No Matches
cc1_main.cpp
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/DiagnosticSema.h>
16#undef CALLBACK
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/Stack.h"
19#include "clang/Basic/TargetOptions.h"
20#if __has_include("clang/CodeGen/ObjectFilePCHContainerOperations.h")
21#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
22#endif
23#include "clang/Config/config.h"
24#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/CompilerInvocation.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/TextDiagnosticBuffer.h"
28#include "clang/Frontend/TextDiagnosticPrinter.h"
29#include "clang/FrontendTool/Utils.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/LinkAllPasses.h"
32#include "llvm/Option/Arg.h"
33#include "llvm/Option/ArgList.h"
34#include "llvm/Option/OptTable.h"
35#include "llvm/Support/BuryPointer.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/Process.h"
41#include "llvm/Support/Signals.h"
42//#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
44#include "llvm/Support/TimeProfiler.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Target/TargetMachine.h"
48
49#include <iostream>
50#include <sstream>
51
52#ifdef CLANG_HAVE_RLIMITS
53#include <sys/resource.h>
54#endif
55
56using namespace clang;
57using namespace llvm::opt;
58
59class QtDiagnosticConsumer final : public DiagnosticConsumer
60{
61
62 // DiagnosticConsumer interface
63public:
64#if LLVM_VERSION_MAJOR < 23
65 void finish() override { std::cerr << " == finish == \n"; }
66#endif
67 void
68 HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic& Info) override
69 {
70 SmallVector<char, 1024> vec;
71 Info.FormatDiagnostic(vec);
72 std::cerr << " == diagnostic == " << vec.data() << "\n";
73 }
74};
75
76//===----------------------------------------------------------------------===//
77// Main driver
78//===----------------------------------------------------------------------===//
79#if LLVM_VERSION_MAJOR < 14
80static void
81LLVMErrorHandler(void* UserData, const std::string& Message, bool GenCrashDiag)
82#else
83static void LLVMErrorHandler(void* UserData, const char* Message, bool GenCrashDiag)
84#endif
85{
86 DiagnosticsEngine& Diags = *static_cast<DiagnosticsEngine*>(UserData);
87
88 Diags.Report(diag::err_fe_error_backend) << Message;
89
90 // Run the interrupt handlers to make sure any special cleanups get done, in
91 // particular that we remove files registered with RemoveFileOnSignal.
92 llvm::sys::RunInterruptHandlers();
93
94 // We cannot recover from llvm errors. When reporting a fatal error, exit
95 // with status 70 to generate crash diagnostics. For BSD systems this is
96 // defined as an internal software error. Otherwise, exit with status 1.
97 llvm::sys::Process::Exit(GenCrashDiag ? 70 : 1);
98}
99
100#ifdef CLANG_HAVE_RLIMITS
101#if defined(__linux__) && defined(__PIE__)
102static size_t getCurrentStackAllocation()
103{
104 // If we can't compute the current stack usage, allow for 512K of command
105 // line arguments and environment.
106 size_t Usage = 512 * 1024;
107 if(FILE* StatFile = fopen("/proc/self/stat", "r"))
108 {
109 // We assume that the stack extends from its current address to the end of
110 // the environment space. In reality, there is another string literal (the
111 // program name) after the environment, but this is close enough (we only
112 // need to be within 100K or so).
113 unsigned long StackPtr, EnvEnd;
114 // Disable silly GCC -Wformat warning that complains about length
115 // modifiers on ignored format specifiers. We want to retain these
116 // for documentation purposes even though they have no effect.
117#if defined(__GNUC__) && !defined(__clang__)
118#pragma GCC diagnostic push
119#pragma GCC diagnostic ignored "-Wformat"
120#endif
121 if(fscanf(
122 StatFile,
123 "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
124 "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
125 "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
126 "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
127 &StackPtr, &EnvEnd)
128 == 2)
129 {
130#if defined(__GNUC__) && !defined(__clang__)
131#pragma GCC diagnostic pop
132#endif
133 Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
134 }
135 fclose(StatFile);
136 }
137 return Usage;
138}
139
140#include <alloca.h>
141
142LLVM_ATTRIBUTE_NOINLINE
143static void ensureStackAddressSpace()
144{
145 // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
146 // relatively close to the stack (they are only guaranteed to be 128MiB
147 // apart). This results in crashes if we happen to heap-allocate more than
148 // 128MiB before we reach our stack high-water mark.
149 //
150 // To avoid these crashes, ensure that we have sufficient virtual memory
151 // pages allocated before we start running.
152 size_t Curr = getCurrentStackAllocation();
153 const int kTargetStack = DesiredStackSize - 256 * 1024;
154 if(Curr < kTargetStack)
155 {
156 volatile char* volatile Alloc
157 = static_cast<volatile char*>(alloca(kTargetStack - Curr));
158 Alloc[0] = 0;
159 Alloc[kTargetStack - Curr - 1] = 0;
160 }
161}
162#else
163static void ensureStackAddressSpace() { }
164#endif
165
167static void ensureSufficientStack()
168{
169 struct rlimit rlim;
170 if(getrlimit(RLIMIT_STACK, &rlim) != 0)
171 return;
172
173 // Increase the soft stack limit to our desired level, if necessary and
174 // possible.
175 if(rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < rlim_t(DesiredStackSize))
176 {
177 // Try to allocate sufficient stack.
178 if(rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max >= rlim_t(DesiredStackSize))
179 rlim.rlim_cur = DesiredStackSize;
180 else if(rlim.rlim_cur == rlim.rlim_max)
181 return;
182 else
183 rlim.rlim_cur = rlim.rlim_max;
184
185 if(setrlimit(RLIMIT_STACK, &rlim) != 0 || rlim.rlim_cur != DesiredStackSize)
186 return;
187 }
188
189 // We should now have a stack of size at least DesiredStackSize. Ensure
190 // that we can actually use that much, if necessary.
191 ensureStackAddressSpace();
192}
193#else
194static void ensureSufficientStack() { }
195#endif
196
197auto printErrors(TextDiagnosticBuffer& buf, const SourceManager& mgr)
198{
199 std::stringstream ss;
200 for(auto it = buf.err_begin(); it != buf.err_end(); ++it)
201 {
202 auto& loc = it->first;
203 ss << loc.printToString(mgr) << ":\n" << it->second << "\n\n";
204 }
205
206 std::cerr << ss.str();
207 return ss.str();
208}
209llvm::Error cc1_main(ArrayRef<const char*> Argv, const char* Argv0, void* MainAddr)
210{
211 ensureSufficientStack();
212
213 // Initialize targets first, so that --version shows registered targets.
214 llvm::InitializeAllTargets();
215 llvm::InitializeAllTargetMCs();
216 llvm::InitializeAllAsmPrinters();
217 llvm::InitializeAllAsmParsers();
218
219 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
220#ifdef LINK_POLLY_INTO_TOOLS
221 llvm::PassRegistry& Registry = *llvm::PassRegistry::getPassRegistry();
222 polly::initializePollyPasses(Registry);
223#endif
224
225 // Buffer diagnostics from argument parsing so that we can output them using a
226 // well formed diagnostic object.
227#if LLVM_VERSION_MAJOR >= 21
228 DiagnosticOptions DiagOpts;
229#else
230 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
231#endif
232 TextDiagnosticBuffer* DiagsBuffer = new TextDiagnosticBuffer;
233 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(new DiagnosticsEngine(
234 DiagID,
235#if LLVM_VERSION_MAJOR >= 21
236 DiagOpts,
237#else
238 &*DiagOpts,
239#endif
240 DiagsBuffer));
241
242#if LLVM_VERSION_MAJOR >= 13
243 llvm::IntrusiveRefCntPtr<FileManager> Files(
244 new FileManager(FileSystemOptions(), llvm::vfs::getRealFileSystem()));
245 llvm::IntrusiveRefCntPtr<SourceManager> SrcMgr(new SourceManager(*Diags, *Files));
246#endif
247
248 // Create a Clang instance
249 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
250
251#if __has_include("clang/CodeGen/ObjectFilePCHContainerOperations.h")
252 // Register the support for object-file-wrapped Clang modules.
253 auto PCHOps = Clang->getPCHContainerOperations();
254 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
255 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
256#endif
257
258 bool Success
259 = CompilerInvocation::CreateFromArgs(Clang->getInvocation(), Argv, *Diags);
260
261#if LLVM_VERSION_MAJOR >= 13
262 if(!Clang->hasSourceManager())
263 {
264 Diags->setSourceManager(SrcMgr.get());
265
266 Clang->setFileManager(Files.get());
267 Clang->setSourceManager(SrcMgr.get());
268 }
269#endif
270 // Infer the builtin include path if unspecified.
271
272#if LLVM_VERSION_MAJOR < 22
273 if(Clang->getHeaderSearchOpts().UseBuiltinIncludes
274 && Clang->getHeaderSearchOpts().ResourceDir.empty())
275 Clang->getHeaderSearchOpts().ResourceDir
276 = CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
277#endif
278
279 Clang->setDiagnostics(Diags.get());
280 if(!Clang->hasDiagnostics())
281 {
282 return llvm::make_error<llvm::StringError>(
283 "No diagnostics", std::error_code(1, std::system_category()));
284 }
285
286 // Set an error handler, so that any LLVM backend diagnostics go through our
287 // error handler.
288 llvm::install_fatal_error_handler(
289 LLVMErrorHandler, static_cast<void*>(&Clang->getDiagnostics()));
290
291 //if(Clang && DiagsBuffer)
292 // DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
293 Clang->getDiagnostics().setSeverity(clang::diag::ext_constexpr_function_never_constant_expr, diag::Severity::Ignored, {});
294 if(!Success)
295 {
296 return llvm::make_error<llvm::StringError>(
297 printErrors(*DiagsBuffer, Clang->getSourceManager()),
298 std::error_code(1, std::system_category()));
299 }
300
301 // Execute the frontend actions.
302 {
303 llvm::TimeTraceScope TimeScope("ExecuteCompiler");
304 Success = ExecuteCompilerInvocation(Clang.get());
305 }
306
307 // If any timers were active but haven't been destroyed yet, print their
308 // results now. This happens in -disable-free mode.
309 llvm::TimerGroup::printAll(llvm::errs());
310 llvm::TimerGroup::clearAll();
311
312 auto res = Success ? llvm::Error::success()
313 : llvm::make_error<llvm::StringError>(
314 printErrors(*DiagsBuffer, Clang->getSourceManager()),
315 std::error_code(1, std::system_category()));
316
317 // Our error handler depends on the Diagnostics object, which we're
318 // potentially about to delete. Uninstall the handler now so that any
319 // later errors use the default handling behavior instead.
320 llvm::remove_fatal_error_handler();
321
322 // When running with -disable-free, don't do any destruction or shutdown.
323 if(Clang->getFrontendOpts().DisableFree)
324 {
325 llvm::BuryPointer(std::move(Clang));
326 return res;
327 }
328 return res;
329}
Definition cc1_main.cpp:60
STL namespace.