1 //===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
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 // This is the entry point to the clang -cc1 functionality, which implements the
11 // core compiler functionality along with a number of additional tools for
12 // demonstration and testing purposes.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Option/Arg.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/LinkAllPasses.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cstdio>
40 
41 #ifdef CLANG_HAVE_RLIMITS
42 #include <sys/resource.h>
43 #endif
44 
45 using namespace clang;
46 using namespace llvm::opt;
47 
48 //===----------------------------------------------------------------------===//
49 // Main driver
50 //===----------------------------------------------------------------------===//
51 
52 static void LLVMErrorHandler(void *UserData, const std::string &Message,
53                              bool GenCrashDiag) {
54   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
55 
56   Diags.Report(diag::err_fe_error_backend) << Message;
57 
58   // Run the interrupt handlers to make sure any special cleanups get done, in
59   // particular that we remove files registered with RemoveFileOnSignal.
60   llvm::sys::RunInterruptHandlers();
61 
62   // We cannot recover from llvm errors.  When reporting a fatal error, exit
63   // with status 70 to generate crash diagnostics.  For BSD systems this is
64   // defined as an internal software error.  Otherwise, exit with status 1.
65   exit(GenCrashDiag ? 70 : 1);
66 }
67 
68 #ifdef LINK_POLLY_INTO_TOOLS
69 namespace polly {
70 void initializePollyPasses(llvm::PassRegistry &Registry);
71 }
72 #endif
73 
74 #ifdef CLANG_HAVE_RLIMITS
75 // The amount of stack we think is "sufficient". If less than this much is
76 // available, we may be unable to reach our template instantiation depth
77 // limit and other similar limits.
78 // FIXME: Unify this with the stack we request when spawning a thread to build
79 // a module.
80 static const int kSufficientStack = 8 << 20;
81 
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     if (fscanf(StatFile,
94                "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
95                "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
96                "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
97                "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
98                &StackPtr, &EnvEnd) == 2) {
99       Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
100     }
101     fclose(StatFile);
102   }
103   return Usage;
104 }
105 
106 #include <alloca.h>
107 
108 LLVM_ATTRIBUTE_NOINLINE
109 static void ensureStackAddressSpace(int ExtraChunks = 0) {
110   // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
111   // relatively close to the stack (they are only guaranteed to be 128MiB
112   // apart). This results in crashes if we happen to heap-allocate more than
113   // 128MiB before we reach our stack high-water mark.
114   //
115   // To avoid these crashes, ensure that we have sufficient virtual memory
116   // pages allocated before we start running.
117   size_t Curr = getCurrentStackAllocation();
118   const int kTargetStack = kSufficientStack - 256 * 1024;
119   if (Curr < kTargetStack) {
120     volatile char *volatile Alloc =
121         static_cast<volatile char *>(alloca(kTargetStack - Curr));
122     Alloc[0] = 0;
123     Alloc[kTargetStack - Curr - 1] = 0;
124   }
125 }
126 #else
127 static void ensureStackAddressSpace() {}
128 #endif
129 
130 /// Attempt to ensure that we have at least 8MiB of usable stack space.
131 static void ensureSufficientStack() {
132   struct rlimit rlim;
133   if (getrlimit(RLIMIT_STACK, &rlim) != 0)
134     return;
135 
136   // Increase the soft stack limit to our desired level, if necessary and
137   // possible.
138   if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < kSufficientStack) {
139     // Try to allocate sufficient stack.
140     if (rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max >= kSufficientStack)
141       rlim.rlim_cur = kSufficientStack;
142     else if (rlim.rlim_cur == rlim.rlim_max)
143       return;
144     else
145       rlim.rlim_cur = rlim.rlim_max;
146 
147     if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
148         rlim.rlim_cur != kSufficientStack)
149       return;
150   }
151 
152   // We should now have a stack of size at least kSufficientStack. Ensure
153   // that we can actually use that much, if necessary.
154   ensureStackAddressSpace();
155 }
156 #else
157 static void ensureSufficientStack() {}
158 #endif
159 
160 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
161   ensureSufficientStack();
162 
163   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
164   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
165 
166   // Register the support for object-file-wrapped Clang modules.
167   auto PCHOps = Clang->getPCHContainerOperations();
168   PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
169   PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
170 
171   // Initialize targets first, so that --version shows registered targets.
172   llvm::InitializeAllTargets();
173   llvm::InitializeAllTargetMCs();
174   llvm::InitializeAllAsmPrinters();
175   llvm::InitializeAllAsmParsers();
176 
177 #ifdef LINK_POLLY_INTO_TOOLS
178   llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
179   polly::initializePollyPasses(Registry);
180 #endif
181 
182   // Buffer diagnostics from argument parsing so that we can output them using a
183   // well formed diagnostic object.
184   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
185   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
186   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
187   bool Success = CompilerInvocation::CreateFromArgs(
188       Clang->getInvocation(), Argv.begin(), Argv.end(), Diags);
189 
190   // Infer the builtin include path if unspecified.
191   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
192       Clang->getHeaderSearchOpts().ResourceDir.empty())
193     Clang->getHeaderSearchOpts().ResourceDir =
194       CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
195 
196   // Create the actual diagnostics engine.
197   Clang->createDiagnostics();
198   if (!Clang->hasDiagnostics())
199     return 1;
200 
201   // Set an error handler, so that any LLVM backend diagnostics go through our
202   // error handler.
203   llvm::install_fatal_error_handler(LLVMErrorHandler,
204                                   static_cast<void*>(&Clang->getDiagnostics()));
205 
206   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
207   if (!Success)
208     return 1;
209 
210   // Execute the frontend actions.
211   Success = ExecuteCompilerInvocation(Clang.get());
212 
213   // If any timers were active but haven't been destroyed yet, print their
214   // results now.  This happens in -disable-free mode.
215   llvm::TimerGroup::printAll(llvm::errs());
216 
217   // Our error handler depends on the Diagnostics object, which we're
218   // potentially about to delete. Uninstall the handler now so that any
219   // later errors use the default handling behavior instead.
220   llvm::remove_fatal_error_handler();
221 
222   // When running with -disable-free, don't do any destruction or shutdown.
223   if (Clang->getFrontendOpts().DisableFree) {
224     BuryPointer(std::move(Clang));
225     return !Success;
226   }
227 
228   return !Success;
229 }
230