cc1_main.cpp 10 KB

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