cc1_main.cpp 10 KB

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